Check Laravel JWT token is valid or not

Create Middleware using the below command

Command: php artisan make:middleware JwtMiddleware


Paste the below code:

<?php

namespace App\Http\Middleware;

use Closure;

use JWTAuth;

use Exception;

use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware

{

    /**

     * Handle incoming requests.

     * @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){

                return response()->json(['status' => 'Token is Invalid']);

            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){

                return response()->json(['status' => 'Token is Expired']);

            }else{

                return response()->json(['status' => 'Authorization Token not found']);

            }

        }

        return $next($request);

    }

}

To use this middleware register this into Kernel. Open app\Http\Kernel.php


...

protected $routeMiddleware = [

...

        'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,

        'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',

        'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',

    ];

...

This middleware will verify that the user is authenticated by checking the token sent in the request’s header and It will create a new middleware file in your Middleware directory. . In case of a user is not authenticated middleware throw an UnauthorizedHttpException exception.

Comments

Popular posts from this blog

Android App Version Update using the following cordova cli commands

75 inspirational quotes that will change your life

Retrieval Image From DataBase and Display on WebPage by Using Servlets.