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
- Check the previous exception in the server log to see the underlying TypeError/Error
- Verify the length passed to setEncryptionKey/random generation is a positive integer (the code throws DomainException for non-positive lengths before random_bytes)
- Inspect PHP configuration for the CSPRNG (open_basedir/paths to /dev/urandom, php.ini) on the server
- 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
- Keep token/identifier length configuration as a positive integer
- Check server logs for the chained previous exception to find the root cause
- Verify random_bytes works on deployment targets (php -r 'echo bin2hex(random_bytes(8));')
- Pin a healthy PHP runtime version in CI and production
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)