Laravel JWT-Auth: Refresh token on Auto-Pilot

Andino Inyang
2 min readJun 8, 2020

--

So let’s assume you’ve built an API, and you need to automate refreshing of tokens. Well Laravel makes this easy without manually keeping track of access_token, refresh_token, expired_in.

Disclaimer: This tutorial assumes you know how to set up tymondesigns\Jwt-Auth with Laravel, if not please refer to this article before you continue.

There are different implementations used in refreshing tokens in Laravel micro-service-based systems, here are some of the commonly used:

  1. Extend Tymon BaseMiddleware.
  2. Create a refresh route; front-end apps decipher token expiring time and calls the refresh route to update.

Extend Tymon BaseMiddleware
Open terminal in your project root, and run the command below to create a new custom middleware.

$ php artisan make:middleware JwtMiddleware

This file can be located here app/Http/Middleware/JwtMiddleware. Open up the file and replace the content with the following:

$<?phpnamespace App\Http\Middleware;use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class JwtMiddleware extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next){
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
$status = 401;
$message = 'This token is invalid. Please Login';
return response()->json(compact('status','message'),401);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
// If the token is expired, then it will be refreshed and added to the headers
try
{
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
$request->headers->set('Authorization','Bearer '.$refreshed);
}catch (JWTException $e){
return response()->json([
'code' => 103,
'message' => 'Token cannot be refreshed, please Login again'
]);
}
}else{
$message = 'Authorization Token not found';
return response()->json(compact('message'), 404);
}
}
return $next($request);
}
}

In the snippet above, when the token is expired, a new token is generated from the expired token and is added to the response headers. The calling app needs to check if the response has been updated and save the updated token against the next request.

CONCLUSION

Continue learning in part 2 of this series. Till we meet again Happy coding!

Hire me:

Email: inyangandino@gmail.com

LinkedIn: Andino Inyang

Thank you for reading my article. Here at my blog or medium I regularly write about backend development, digital marketing and content management system. To read my future posts simply join my publication or click ‘Follow’ Also feel free to connect with me via Twitter, Facebook, Instagram.

If you are interested in backend development (or you’re internet enthusiast) both (Mobile | Web | Desktop) videos subscribe to my Youtube channel, we will be posting a collection of help full tutorials and guides like this one for artisans.

If you enjoy this post, make sure to let us know and share it with your friends and subscribe to my growing channel.

Sharing is caring.

--

--

Andino Inyang

Experienced Product Analyst skilled in market research, experiment management, strategy development, and cross-functional collaboration.