In this tutorial you will learn about the Laravel 7 jwt Authentication Rest API Tutorial and its application with practical example.
In this Laravel 7 jwt Authentication Rest API Tutorial I’ll show you how to build the rest APIs with jwt (JSON web token) authentication in laravel 7. In this example I’ll also show you how to install jwt auth and configure jwt auth in laravel 7. In this article, we will learn to create fully functional restful API with JWT Authentication in Laravel 7. In this tutorial, we will be creating fully functional REST API along with JWT Authentication.
Laravel 7 jwt Authentication Rest API Tutorial
- Step 1: Install Laravel 7/6/5 App
- Step 2: Configure Database
- Step 3: Install jwt laravel
- Step 4: Configure jwt in laravel
- Step 5: Generate jwt secret key
- Step 6: Add jwt Class in Model
- Step 7: Add Api Routes
- Step 8: Create Api Controller
- Step 9: Run Development Server
Step 1: Install Laravel 7/6/5 App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: 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.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Step 3: Install jwt laravel
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 |
Step 4: Configure jwt in laravel
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', ], |
After that, run the below given command to publish the configuration file in Laravel for jwt auth:
1 |
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider" |
Step 5: Generate jwt secret key
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 |
public function handle() { $this->fire(); } |
Step 6: Add jwt Class in Model
In this step, Navigate to App folder and open User.php file. Then update the following code into User.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; } |
Step 7: Add Api Routes
1 2 3 4 5 6 7 8 |
Route::post('login', 'JwtAuthController@login'); Route::post('register', 'JwtAuthController@register'); Route::group(['middleware' => 'auth.jwt'], function () { Route::get('logout', 'JwtAuthController@logout'); Route::get('user-info', 'JwtAuthController@getUser'); }); |
Step 8: Create Api Controller
1 |
php artisan make:controller JwtAuthController |
After that, you need to create some methods in JwtAuthController.php. So go to app/http/controllers/ and open JwtAuthController.php file. Then put 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 |
<?php namespace App\Http\Controllers; use JWTAuth; use Validator; use App\User; use Illuminate\Http\Request; use App\Http\Requests\RegisterAuthRequest; 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]); } } |
Step 9: Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |