jwt auth in laravel. Here, we will show you how to create rest api using tymon/jwt-auth laravel 7/6/5.
This tutorial will guide you step by step on how to install jwt in laravel and create rest api using tymon/jwt-auth laravel 7/6/5.
Laravel 7/6/5 jwt Authentication Tutorial
Use the below given steps to create rest api using jwt auth in laravel 7/6/5:
- 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, run the following command on your command prompt to install laravel fresh setup for building laravel 7/6/5 jwt auth Apis app:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Configure Database
Then, Navigate root directory of your installed laravel restful authentication api with passport tutorial project. And open .env file. Then add the database details as follow:
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, run the below command and install jwt auth package :
composer require tymon/jwt-auth
Step 4: Configure jwt in laravel
After successfully install jwt auth laravel. So, Open config/app.php and add jwt providers and aliases:
'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:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
Step 5: Generate jwt secret key
In this step, Run the following command to generate jwt key secret:
php artisan jwt:generate
If you find an error like this after hit the above command.
“ReflectionException : Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist“
Now, open JWTGenerateCommand.php file. So, navigate to vendor/tymon/src/Commands/JWTGenerateCommand.php and update the code:
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:
<?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
In this step, you need to create rest API routes for laravel restful authentication apis with passport project.
So, navigate to routes folder and open api.php. Then update the following routes into api.php file:
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
In this step, you need to create a controller name JwtAuthController. Use the below command and create a controller :
php artisan make:controller JwtAuthController
After that, you need to create some methods in JwtAuthController.php. So navigate to app/http/controllers/ and open JwtAuthController.php file. Then update the following methods into your JwtAuthController.php file:
<?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
Finally, run the following command on terminal to start developement server. And call api with required parameters:
php artisan serve