JWT Auth

Laravel Auth: JWT Auth

tymondesigns/jwt-auth

Install

composer require tymon/jwt-auth:^1.0

Publish the config

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Generate secret key

This will update your .env file with something like JWT_SECRET=foobar

php artisan jwt:secret

Maintain the JWT Token Manually

Set Secret Key

JWTAuth::manager()->getJWTProvider()->setSecret('secret_key');

Set Expire Minutes

JWTFactory::setTTL(30);

Set Refresh Token Minutes

JWTAuth::factory()->validator()->setRefreshTTL(180);

Make JWT Token

public static function makeJWTToken(array $claim_list)
{
    // Generate payload
    $payload = JWTFactory::customClaims($claim_list)->make();
    // Encrypt Payload
    $token = JWTAuth::encode($payload);
    
    return $token;
}

public static function makeUserModelToken(UserModel $UserModel)
{
    $payload = [
        'sub' => $UserModel->id,
    ];
    $UserModelJWTToken = static::makeToken($payload);
    $user_token = $UserModelJWTToken->get();
    return $user_token;
}

Get JWT Token Payload

public static function getJWTTokenPayload($token)
{
    try {
        $payload = JWTAuth::setToken($token)->getPayload();
        return $payload;
    } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $exception) {
        // Token Expired
        
    } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $exception) {
        // Token Invalid
    }
}

public static function getJWTTokenPayloadClaimList($token)
{
    $payload = static::getJWTTokenPayload($token);
    return $payload->toArray();
}

Refresh JWT Token

public static function refreshJWTToken($token)
{
    try {
        $token = JWTAuth::setToken($token)->refresh();
        return $token;
    } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $exception) {
        // Token Expired
    } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $exception) {
        // Token Invalid
    }
}

Reference