Reputation: 612
I am writing an application in Laravel5 that communicates with an API, how can I keep authenticated with the API even after my JWT Token expired. The login credentials are stored in the environment file. The first time I login and save the token to the session. Then I have a token but it can expire and returns a 401 with the message
{
"message": "Token expired"
}
How can I detect this without the user noticing that the application had to re-authenticate, can I use middleware for this to catch the 401 with the message Token expired and then authenticate again and store a new token?
The flow is like this.
User requests url on my application
->
My application asks for data from the API
->
Checks the Token in my storage with that one in the API
->
Returns 401 with message Token expired
->
Requests a new Token
->
Returns data from API to user.
I have to do this all and my user should not notice it and I don't want to authenticate to the api on every request. But I have no idea where to start.
Upvotes: 0
Views: 316
Reputation: 1892
Good question.
This can be achieved via Refresh Tokens, if you're using the Laravel JWT Package found:
You are able to utilise refresh tokens realtively easily. You can add a middleware like:
protected $routeMiddleware = [
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
];
During your step:
Checks the Token in my storage with that one in the API
If the token has expired but the refresh time is still valid, you will be returned the refresh token in the header, assuming the route you hit is in the jwt.refresh middleware.
Let me know if you need any additional help.
Full docs here:
Upvotes: 1