Skip to content

Instantly share code, notes, and snippets.

@1isten
Last active December 31, 2019 15:25
Show Gist options
  • Save 1isten/a83f8d7bf0de694af5c653efec19a441 to your computer and use it in GitHub Desktop.
Save 1isten/a83f8d7bf0de694af5c653efec19a441 to your computer and use it in GitHub Desktop.
Use Laravel Passport to create and manage JWT Tokens (Personal Access Tokens)

Setup according to the documentation

  • Keep the default migrations as token info will be stored at db
  • Personal Access Token is what we will use as JWT
  • Token lifetime can be set in AuthServiceProvider via personalAccessTokensExpireIn
  • No need to use CreateFreshApiToken middleware
  • Client should store tokens using JavaScript (e.g., localStorage, or js-cookie)
  • Client should append the 'Authorization': 'Bearer xxx' header manually

Create the token, use the createToken method

$jwt = $user->createToken('jwt');

return response()->json([
    'token' => $jwt->accessToken,
    'tokenExp' => $jwt->token->expires_at,
], 200);

Use the auth:api middleware

Route::middleware('auth:api')->get('/user', function (Request $request) {
    $user = $request->user();
    $token = $user->token();

    // expired token still passes the auth:api middleware
    // so we need to check it manually
    if ($token->expires_at < Illuminate\Support\Carbon::now()) {
        // revoke the token
        $token->revoke(); // ⮑ true, $token->revoked will be set to 1
        // or, delete the token
        $token->delete(); // ⮑ true, token info will be removed from db

        return response()->json([
            'error' => 'Unauthenticated.'
        ], 401);
    }

    return $user;
});

Delete invalid tokens

$revoked_tokens = $user->tokens->where('revoked', true);
foreach ($revoked_tokens as $revoked_token) {
    $revoked_token->delete();
}

$expired_tokens = $user->tokens->where('expires_at', '<', Illuminate\Support\Carbon::now());
foreach ($expired_tokens as $expired_token) {
    $expired_token->delete();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment