thephpleague/oauth2-server · critical · OAuthServerException

server_error

server_error

Error message

An unexpected error has occurred

What it means

A generic 500-class server error raised inside generateUniqueIdentifier when random_bytes() or bin2hex() throws a TypeError or Error (PHP engine-level failures), typically due to invalid $length (zero/negative/non-int) or an unavailable CSPRNG. It is wrapped as OAuthServerException::serverError with the previous exception attached for diagnostics.

Solutions

  1. Check the previous exception in the server log to see the underlying TypeError/Error
  2. Verify the length passed to setEncryptionKey/random generation is a positive integer (the code throws DomainException for non-positive lengths before random_bytes)
  3. Inspect PHP configuration for the CSPRNG (open_basedir/paths to /dev/urandom, php.ini) on the server
  4. Update PHP to a version where random_bytes is reliably available (PHP 7+ with a healthy engine install)

Example fix

// before
$server->setAccessTokenLength(0);
// after
$server->setAccessTokenLength(40); // positive integer
Defensive patterns

Strategy: try-catch

Validate before calling

const len = serverConfig.tokenLength;
if (!Number.isInteger(len) || len <= 0) throw new Error('token length must be a positive integer');

Type guard

function isValidLength(n: unknown): n is number { return typeof n === 'number' && Number.isInteger(n) && n > 0; }

Try / catch

try {
  return await grant.issueAccessToken(...);
} catch (e) {
  if (e.code === 'server_error' && e.previous) {
    logger.error('random generation failed', e.previous);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling issueAccessToken, issueAuthCode, issueRefreshToken, or issueDeviceCode when random_bytes($length) receives an invalid argument (e.g. length <= 0 or a non-integer from misconfiguration) or when the engine raises an unexpected Error during random generation.

Common situations: A config value or constant supplying the token length was changed to 0 or a string, a PHP version/platform where the CSPRNG is unavailable or misconfigured (e.g. broken php.ini random settings), or a custom grant subclassing AbstractGrant passes a bad length.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of thephpleague/oauth2-server@9d2f6fc0a0 (2026-09-15). Data as JSON: /api/errors/a7c75be5c90c5b67. Report an issue: GitHub.

Appendix: source

Thrown at src/Grant/AbstractGrant.php:549

    /**
     * Generate a new unique identifier.
     *
     * @return non-empty-string
     *
     * @throws OAuthServerException
     */
    protected function generateUniqueIdentifier(int $length = 40): string
    {
        try {
            if ($length < 1) {
                throw new DomainException('Length must be a positive integer');
            }

            return bin2hex(random_bytes($length));
            // @codeCoverageIgnoreStart
        } catch (TypeError | Error $e) {
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
        } catch (Exception $e) {
            // If you get this message, the CSPRNG failed hard.
            throw OAuthServerException::serverError('Could not generate a random string', $e);
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * {@inheritdoc}
     */
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request): bool
    {
        $requestParameters = (array) $request->getParsedBody();

        return (
            array_key_exists('grant_type', $requestParameters)
            && $requestParameters['grant_type'] === $this->getIdentifier()
        );

View on GitHub (pinned to 9d2f6fc0a0)