Laravel JWT-Auth: Refresh token on Auto-Pilot (series 2)
In a previous article, we covered the basics of authenticating users with JSON Web Tokens (JWT) in Laravel using the tymondesigns/jwt-auth package. We also saw how to use the package’s simple interface to create, encode, and decode JWTs.
In this article, we will continue our exploration of JWT by discussing how to refresh a token once it has expired. By default, a JWT token created in Laravel will be valid for a specific period of time (usually one hour). If a user attempts to access a protected route after this time period has expired, they will receive a TokenExpiredException
. To handle this exception, we can create a middleware that will automatically refresh the token for the user.
Here are a few examples of how you can refresh JWT tokens in Laravel using the tymondesigns/jwt-auth package:
- Using the
refresh
method:
$newToken = JWTAuth::refresh();
This method will refresh the current token and return the new token.
2. Using the parseToken
and refresh
methods:
$token = JWTAuth::getToken();
$newToken = JWTAuth::refresh($token);
This method allows you to refresh a specific token rather than the current token.