In this tutorial you will learn about the Laravel 8 JWT Rest API Authentication Example Tutorial and its application with practical example.
In this Laravel 8 JWT Rest API Authentication Example Tutorial I’ll show you how to build the rest APIs with jwt (JSON web token) authentication in laravel 8. In this example I’ll also show you how to install jwt auth and configure jwt auth in laravel 8.
In one of my previous articles, we have learn How to Create REST API With Passport Authentication In Laravel 8 using Laravel passport for REST API authentication. In this article, we will learn to create fully functional restful API with JWT Authentication in Laravel 8. In this tutorial, we will be creating fully functional REST API along with JWT Authentication.
Laravel 8 JWT Rest API Authentication Example Tutorial
In this laravel step by step tutorial you will learn how to create REST API with Laravel 8 using JWT Token (JSON Web Token). Please follow the step given bellow:
- Download Laravel 8 App
- Database Configuration
- Install JWT Auth
- Registering Middleware
- Run Migration
- Create APIs Route
- Create JWT Auth Controller
- Now Test Laravel REST API in Postman
Install Laravel 8
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel lara8blog |
Configure Database
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=lara8blog DB_USERNAME=root DB_PASSWORD= |
Install JWT Auth
In this step, we will install tymon jwt auth package via the composer dependency manager. Use the following command to install laravel jwt authentication package.
1 |
composer require tymon/jwt-auth |
After Installing tymon/jwt-auth package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 |
'providers' => [ …. 'Tymon\JWTAuth\Providers\JWTAuthServiceProvider', ], 'aliases' => [ …. 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth', 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory', ], |
Now, you need to generate jwt encryption keys. Use the following command to generate encryption keys needed to generate secure access tokens:
1 |
php artisan jwt:generate |
Now, open JWTGenerateCommand.php file and put the following code,
vendor/tymon/src/Commands/JWTGenerateCommand.php
1 2 3 4 5 |
public function handle() { $this->fire(); } |
Registering Middleware
Register auth.jwt middleware in app/Http/Kernel.php
app/Http/Kernel.php
1 2 3 4 5 |
protected $routeMiddleware = [ 'auth.jwt' => 'auth.jwt' => 'Tymon\JWTAuth\Middleware\GetUserFromToken', ]; |
Run Migration
Now, you need to run migration using the following command to create tables in the database :
1 |
php artisan migrate |
Create APIs Route
Now we will create rest API auth routes. Go to the routes directory and open api.php. Then put the following routes into api.php file:
routes/api.php
1 2 3 4 5 6 7 8 9 10 |
use App\Http\Controllers\API\JWTAuthController; Route::post('register', [JWTAuthController::class, 'register']); Route::post('login', [JWTAuthController::class, 'login']); Route::group(['middleware' => 'auth.jwt'], function () { Route::post('logout', [JWTAuthController::class, 'logout']); }); |
Create JWT Auth Controller
In this step, we will create a controllers name JWTAuthController. Use the following command to create a controller :
1 |
php artisan make:controller Api\JWTAuthController |
After that, Create some authentication methods in JWTAuthController.php. So navigate to app/http/controllers/API directory and open JWTAuthController.php file. And, update the following methods into your JWTAuthController.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?php namespace App\Http\Controllers\API; use JWTAuth; use Validator; use App\Models\User; use Illuminate\Http\Request; use Tymon\JWTAuth\Exceptions\JWTException; use Symfony\Component\HttpFoundation\Response; class JwtAuthController extends Controller { public $token = true; public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->password = bcrypt($request->password); $user->save(); if ($this->token) { return $this->login($request); } return response()->json([ 'success' => true, 'data' => $user ], Response::HTTP_OK); } public function login(Request $request) { $input = $request->only('email', 'password'); $jwt_token = null; if (!$jwt_token = JWTAuth::attempt($input)) { return response()->json([ 'success' => false, 'message' => 'Invalid Email or Password', ], Response::HTTP_UNAUTHORIZED); } return response()->json([ 'success' => true, 'token' => $jwt_token, ]); } public function logout(Request $request) { $this->validate($request, [ 'token' => 'required' ]); try { JWTAuth::invalidate($request->token); return response()->json([ 'success' => true, 'message' => 'User logged out successfully' ]); } catch (JWTException $exception) { return response()->json([ 'success' => false, 'message' => 'Sorry, the user cannot be logged out' ], Response::HTTP_INTERNAL_SERVER_ERROR); } } public function getUser(Request $request) { $this->validate($request, [ 'token' => 'required' ]); $user = JWTAuth::authenticate($request->token); return response()->json(['user' => $user]); } } |
Then open command prompt and run the following command to start developement server:
1 |
php artisan serve |
Test Laravel 8 REST API with JWT Auth in Postman
Now, we will call above create crud and auth apis in postman app:
1 – Laravel Register Rest API :
2 – Login API :
Next Step, you will call getUser, create product, list product, edit product, and delete product APIs, In this apis need to pass the access token as headers:
1 2 3 4 5 6 7 |
Call login or register apis put $accessToken. ‘headers’ => [ ‘Accept’ => ‘application/json’, ‘Authorization’ => ‘Bearer ‘.$accessToken, ] |