Sunday, 19 April 2020

Jwt authentication in laravel

Jwt authentication in Laravel 5.5 or above

Step 1#: Run the following three command one by one to install the Jwt in your installed Laravel framework.

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret


Step 2#: Update your user model

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

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

   
    public function getJWTCustomClaims()
    {
        return [];
    }

}

Step 3#: Create Auth controller by running this command

php artisan make:controller AuthController
php artisan make:middleware authJwt

add this code to kernel.php

protected $routeMiddleware = [
  ........
'jwt-auth' => \App\Http\Middleware\authJwt::Class,

]

and add the following code to your authcontroller

<?php


namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class AuthController extends Controller { public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } public function me() {

try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
} return response()->json(auth()->user()); } public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } public function refresh() {
try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
}
return $this->respondWithToken(auth()->refresh()); } protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
?>

Step 4#: Create api routes in api.php file.

<?php

Route::group([
'middleware' => 'api', 'prefix' => 'auth' ], function ($router) {
Route::post('login', 'AuthController@login');
Route::get('logout', 'AuthController@logout');
Route::get('refresh', 'AuthController@refresh'); Route::get('me', 'AuthController@me'); });


?>

Step 5#: Test on postman