PHP code example of zotenme / hyperf-jwt-auth

1. Go to this page and download the library: Download zotenme/hyperf-jwt-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zotenme / hyperf-jwt-auth example snippets




use Zotenme\JwtAuth\Contract\JwtManagerInterface;

class AuthController
{
    public function __construct(
        private JwtManagerInterface $jwtManager
    ) {}

    public function login(LoginRequest $request): JsonResponse
    {
        $userId = $this->validateCredentials($request);
        
        $tokenPair = $this->jwtManager->generateTokenPair(
            subjectId: $userId,
            payload: ['role' => 'user', 'permissions' => ['read', 'write']]
        );

        return new JsonResponse([
            'access_token' => $tokenPair->accessToken,
            'refresh_token' => $tokenPair->refreshToken,
            'expires_in' => $tokenPair->accessExpiresIn,
        ]);
    }

    public function refresh(RefreshRequest $request): JsonResponse
    {
        $refreshToken = $request->input('refresh_token');
        $tokenPair = $this->jwtManager->refreshAccessToken($refreshToken);

        return new JsonResponse([
            'access_token' => $tokenPair->accessToken,
            'refresh_token' => $tokenPair->refreshToken,
            'expires_in' => $tokenPair->accessExpiresIn,
        ]);
    }
}



return [
    'algorithm' => 'HS256',
    'keys' => [
        'secret_key' => env('JWT_SECRET'),
    ],
    'access_token' => [
        'ttl' => 900,       // default: 15 minutes
        'max_ttl' => 86400, // maximum dynamic value: 1 day
    ],
    'refresh_token' => [
        'ttl' => 604800,      // default: 7 days
        'max_ttl' => 2592000, // maximum dynamic value: 30 days
        'rotation_enabled' => true,
    ],
    'cache' => [
        'store' => null, // Hyperf's default cache store
        'prefix' => 'jwt_auth:',
    ],
    'blacklist' => ['enabled' => true],
    'sso_mode' => false,
    'issuer' => 'my-api',
    'audience' => ['my-web-app'],
];

use Zotenme\JwtAuth\DTO\TokenOptions;

$tokenPair = $jwtManager->generateTokenPair(
    subjectId: (string) $user->id,
    payload: ['role' => $user->role],
    options: new TokenOptions(
        accessTtl: 3600,      // 1 hour
        refreshTtl: 2592000,  // 30 days
        sessionTtl: 2592000,  // absolute session limit
    ),
);