Aurora Extensions

Logo

Examples, illustrations, UML diagrams, etc.

Token

Table of Contents

Description

Magento provides the Magento\Framework\Math\Random1 class for generating random data. This is particularly useful when you need things like tokens, nonces, and salts.

In the example below, the Token class provides two static methods:

The generate method utilizes random_bytes for random sequence generation, and the isHex method verifies the given sequence contains only hexidecimal characters.

Usage

...
/** @var string $token */
$token = Token::generate();
...

Source

<?php
/**
 * Token.php
 */
declare(strict_types=1);

namespace Vendor\Package\Model\Security;

class Token
{
    /** @constant string REGEX */
    public const REGEX = '/[^a-f0-9]/';

    /**
     * @param int $length
     * @return string
     */
    public static function generate(int $length = 32): string
    {
        return bin2hex(random_bytes($length));
    }

    /**
     * @param string $token
     * @return bool
     */
    public static function isHex(string $token): bool
    {
      return !preg_match(self::REGEX, $token);
    }
}

Notes

  1. Magento\Framework\Math\Random (GitHub)