Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

killerbeast2017's avatar

How to install JWT Auth in Lumen

Could someone shed some light on a step by step guide to include JWT Auth in Lumen? I am totally confused about this.

0 likes
2 replies
Shahrukh4's avatar
  • place "flipbox/lumen-generator": "^5.6", in your composer.json and run composer update

  • place following code in bootstrap/app.php

$app->routeMiddleware([
     'jwt' => App\Http\Middleware\JwtMiddleware::class,    
]);
  • Write following lines in your desired controller
use App\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;

class YourController extends Controller{
        /**
         * Create a new token.
         * 
         * @param  \App\User   $user
        * @return string
        */
        protected function jwt(User $user) {
            $payload = [
                'iss' => "lumen-jwt",                     // Issuer of the token
                'sub' => $user->id,                      // Subject of the token
                'iat' => time(),                        // Time when JWT was issued. 
                'exp' => time() +  config('jwt.app.ttl')// Expiration time
            ];
            return JWT::encode($payload, config('jwt.app.secret'));
       }

       /**
         * Authenticate a user and return the token if the provided credentials are correct.
         * 
         * @param  \App\User   $user 
         * @return mixed
         */
        public function authenticateUser(Request $request) {
              $this->validate($request, [
              'email'     => 'required|email',
              'password'  => 'required'
         ]);

        // Find the user by email
        $user = User::where('email', $request->input('email'))->first();
        if (!$user) {
            return response()->json([
                'error' => 'Email does not exist.'
            ], 400);
        }
        // Verify the password and generate the token
        if (Hash::check($request->input('password'), $user->password)) {
            return response()->json([
                'token' => $this->jwt($user)
            ], 200);
        }
        // Bad Request response
        return response()->json([
            'error' => 'Email or password is wrong.'
        ], 400);
    }
}
  • Write following code in your routes/web.php file,
$router->group(['middleware' => 'jwt'], function () use ($router) {
    $router->post('users', function(){
            return App\User::all();
    });
});

Please or to participate in this conversation.