giovictor
9/9/2019 - 3:24 AM

JWT Setup in Laravel

JWT Setup in Laravel

Installation

Type in CLI

composer require tymon/jwt-auth

Add providers in config/app.php

In Providers array add

Tymon\JWTAuth\Providers\LaravelServiceProvider::class

In Aliases array add

'JWTAuth'=>Tymon\JWTAuth\Facades\JWTAuth::class (optional)

Publish config file and generate secret key

Type in CLI

php artisan vendor:publish "Tymon\JWTAuth\Providers\LaravelServiceProvider::class"

Then a jwt.php file should be found in config directory

php artisan jwt:secret to generate a secret key

Modify the User.php Model

Add use Tymon\JWTAuth\Contracts\JWTSubject

Make sure the User class implements the JWTSubject class then add the following methods:

public function getJWTIdentfier()
{
  return $this->getKey();
}

public function getJWTCustomClaims()
{
  return []; 
}

Exception Handling

use Tymon\JWTAuth\Exceptions\JWTException

Sample Login using JWT

public function login(Request $request)
{
  // Some input validation logic here
  
  $credentials = $request->only(['email','password']);
  
  try {
    if(!$token = auth()->attempt($credentials)) {
      return response()->json(['error'=>'Invalid email or password.'], 401);
    }
  } catch(JWTException $e) {
    return response()->json(['error'=> $e->getMessage()], 500);
  }
  
  return response()->json(['token'=> $token], 200);
  
  // You can add redirect logic in here just make sure to save the token
}

Setup Middleware in app/Http/Middleware/Kernel.php under $routeMiddleware array

'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class

'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class