Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos

Home » Laravel » Laravel 8 Rest API Example With JWT Authentication

Laravel 8 Rest API Example With JWT Authentication

Laravel 8 Rest API Example With JWT Authentication

Posted on November 1, 2020December 15, 2022 By XpertPhp

In this tutorial, we are going on how to create the rest of the API Example with JWT authentication in laravel 8(Laravel 8 Rest API Example With JWT Authentication). so here we are using the tymon/jwt-auth package for the rest API.

The Laravel JWT package is provided by laravel framework. so we can easily create and manage the API in laravel. let’s follow the below steps to how to create the rest API with authentication in laravel.

Overview

Step 1: Install Laravel
Step 2: Setting Database Configuration
Step 3: Install JWT Package
Step 4: Configure Auth guard
Step 5: Registering Middleware
Step 6: Update the User Model
Step 7: Create Route
Step 8: Create a Controller
Step 9: Run The Application

Step 1: Install Laravel
We are going to install laravel 8, so first open the command prompt or terminal and go to xampp htdocs folder directory using the command prompt. after then run the below command.

1
composer create-project --prefer-dist laravel/laravel laravel8_jwt_api

Step 2: Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel8_jwt_api)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Install JWT Package
Now, we are going to install the “tymon/jwt-auth” package using the below command.

1
composer require tymon/jwt-auth

We will add below providers and aliases in the “config/app.php” file.

1
2
3
4
5
6
7
8
9
10
11
'providers' => [
    ....
    ....
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' => [
    ....
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
    ....
],

After the complete set service provider and aliases, we need to run the below command for publishing the package’s configuration.

1
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Now, we will create a Generate jwt secret key using the below command. It will be automatically configure in .env file using the below command.
Step 4: Configure Auth guard
here, in this step, we have to the update guard. so here we will update the token driver to jwt driver in API guards.
config/auth.php

1
2
3
4
5
6
7
8
9
10
11
12
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
 
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

Step 5: Registering Middleware
Now, we need to add middleware in the routeMiddleware array. so you can see the below code.
app/Http/Kernel.php

1
2
3
4
5
protected $routeMiddleware = [
        ....
'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
        'jwt.refresh' => \Tymon\JWTAuth\Http\Middleware\RefreshToken::class,
    ];

Step 6: Update the User Model
Open the User model and update the below code. here we will use the Tymon\JWTAuth\Contracts\JWTSubject package and two methods. like as getJWTIdentifier() and getJWTCustomClaims().
app/Models/User.php

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
<?php
 
namespace App\Models;
 
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
 
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
 
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
/**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier() {
        return $this->getKey();
    }
 
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims() {
        return [];
    }
}

Step 7: Create Route

Add the following route code in the “routes/api.php” file.

1
2
3
4
5
6
7
8
9
10
use App\Http\Controllers\API\UserController;
Route::post('register', [UserController::class, 'register']);
Route::post('login', [UserController::class, 'login'])->name('login');
  
Route::group(['middleware' => 'auth.jwt'], function () {
    Route::get('getuser', [UserController::class, 'getUser']);
    Route::get('logout', [UserController::class, 'logout']);
});

Step 8: Create a Controller
Now, we need to create an API directory and controller file, so first we will create an API directory and UserController.php file. after then created a file then we will create the rest API method. so you can follow the below code.
app/Http/Controllers/API/UserController.php

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
100
101
102
103
104
105
106
107
108
109
110
<?php
 
namespace App\Http\Controllers\API;
 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use JWTAuth;
use Validator;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpFoundation\Response;
 
class UserController 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)
    {
$validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);
if ($validator->fails()) {  
   return response()->json(['error'=>$validator->errors()], 401);
}  
        //$input = $request->only('email', 'password');
        $jwt_token = null;
  
        if (!$jwt_token = JWTAuth::attempt($validator->validated())) {
            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)
    {
        $auth_check = JWTAuth::parseToken()->authenticate();
        if($auth_check){
$user = JWTAuth::authenticate($request->token);
return response()->json(['user' => $user]);
}else{
            return response()->json([
                'success' => false,
                'message' => 'Sorry, token is an invalid'
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}

Step 9: Run The Application
We can start the server and run this application using the below command.

1
php artisan serve

Read Also
Laravel 8 CRUD Operation With Ajax Example
Laravel 8 Rest API CRUD Example With Passport Auth
Laravel 8 Pagination Example Tutorial

Now, you can call the rest API using postman. so we shared some screenshots.
Register API
laravel8_jwt_api_register
Login API
laravel8_jwt_api_login
User Get API

laravel8_jwt_api_getuser

Download

Please follow and like us:
error
fb-share-icon
Tweet
fb-share-icon

Related Posts:

  • Laravel 7 Multiple Authentication Example Tutorial
  • Laravel 8 Multiple Authentication Example Tutorial
  • Laravel 6 Multiple Authentication Example Tutorial
  • Laravel 8 REST API With Passport Authentication Tutorial
  • Laravel 7 REST API With Passport Authentication Tutorial
  • Laravel 6 REST API With Passport Authentication Tutorial
Laravel Tags:Laravel 8, laravel 8 example

Post navigation

Previous Post: Laravel 8 Rest API CRUD Example with Passport Auth
Next Post: Laravel 8 Jetstream Livewire CRUD Example Tutorial

Latest Posts

  • How to disable button in React js
  • JavaScript Interview Questions and Answers
  • JQuery Interview Questions and Answers
  • How to update php 7 to php 8 in xampp on windows
  • How to get the tag name in jQuery
  • how to get html tag in javascript
  • Disable Browser Back Button Using Javascript
  • How to remove file extension using htaccess
  • Matched leaf route at location does not have an element
  • Export ‘Switch’ (Imported As ‘Switch’) Was Not Found In ‘React-Router-Dom’ With Example

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tricks jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch Laravel Socialite laravel social login nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor

Copyright © 2018 - 2023,

All Rights Reserved Powered by XpertPhp.com