Vahid Najafi
Vahid Najafi

Reputation: 5263

Laravel passport get new access token when the token is expired

I want to implement a short time period of the token. Let say 1 day. Also I have auth:api middleware for my route:

Route::middleware('auth:api')->post('auth/test', 'AuthController@test');

When the token gets expired, the user gets logged out (with 401 response code) from the client. Which is not a good idea from the UX point of view. How can I handle it?

Note: I have already implemented such a scenario in CodeIgniter. I had an access token with 10 minutes of expiration time and a very long time refresh token (maybe one year). I had a reference of refresh token in the database. So, within 10 minutes, if the token is valid, there is no need to touch the database. If it's expired, I return a new token to the user, based on refresh token.

Upvotes: 0

Views: 2118

Answers (1)

Saddam
Saddam

Reputation: 1206

One Approach could be to use Middleware on routes,this middleware would perform its task after the request is handled by the application. So in your middleware you can check if the response is 401(Unauthorize) and if so then you can get expired token from header and regenerate new access token from expired token and return it to the user.

Edit Another Approach

If a user does not authenticate, Laravel will throw an AuthenticationException.

This exception is handled by the render method in Illuminate/Foundation/Exceptions/Handler.php, and will in turn call the the unauthenticated() method which is defined in your app/Exceptions/Handler.php: so you can wrote your logic in this method to generate new token from expired one and then return it to the user like

protected function unauthenticated($request, AuthenticationException $exception)
{
    // generate new token and return it to the user and redirect user to the 
    //intended route.

    return redirect()->intended('defaultpage');
}

Upvotes: 1

Related Questions