Laravel 10 JWT Rest API Authentication Tutorial Example

Laravel 10 JWT Rest API Authentication Tutorial Example

If you are creating Rest Office in Laravel Application. And you don’t have knowledge about jwt auth and rest API. So, In this tutorial, you will learn how to create the rest APIs authentication in Laravel 10 using jwt auth.

Laravel 10 JWT Rest API Authentication Tutorial Example

By the following steps, you can create REST API with Laravel 10 apps using JWT Token (JSON Web Token):

  • Step 1: Installing Laravel 10 App
  • Step 2: Connecting App to Database
  • Step 3: Installing JWT Auth in Your Laravel App
  • Step 4: Registering Middleware
  • Step 5: Run Migration
  • Step 6: Create APIs Route
  • Step 7: Create JWT Auth Controller
  • Step 8: Now Test Laravel REST API in Postman

Step 1: Installing Laravel 10 App

First of all, Open command prompt or terminal.

Then execute the following command into it to install Laravel 10 app on your server:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Connecting App to Database

Now, find .env file to configure database details.

So, visit root directory of your installed laravel restful authentication api with jwt 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: Installing JWT Auth in Your Laravel App

In this step, Open again your terminal or command prompt.

And execute the following command into it to install composer require tymon/jwt-auth package:

composer require tymon/jwt-auth

Once you have installed jwt auth in Laravel apps by using the above-given command.

Then register providers and aliases in the app.php file. So, visit the config directory and open app.php. And configure like the following:

  // config/app.php

'providers' => [
….
'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
….
'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
],

Now, you need to generate jwt auth encryption keys. So, execute the command on terminal to create the encryption keys needed to generate secure access tokens:

php artisan jwt:generate

Then open JWTGenerateCommand.php file and paste the following code, Hope it will work.

vendor/tymon/src/Commands/JWTGenerateCommand.php

public function handle() {
 
  $this->fire(); 

}

Step 4: Registering Middleware

Now you need to register to auth.jwt middleware in kernel.php file, which is located inside app/http directory:

protected $routeMiddleware = [

    'auth.jwt' => 'auth.jwt' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',

];

Step 5: Run Migration

In this step, you need to do migration using the bellow command. This command creates tables in the database :

php artisan migrate

Step 6: Create APIs Route

In this step, you need to create rest API routes for laravel restful authentication apis with jwt project.

So, navigate to the routes directory and open api.php. Then update the following routes into api.php file:

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']);
 
});

Step 7: Create JWT Auth Controller

In this step, you need to create a controller name JWTAuthController. Use the below command and create a controller :

 php artisan make:controller Api\JWTAuthController

After that, you need to create some methods in JWTAuthController.php. So navigate to app/http/controllers/API directory and open JWTAuthController.php file. After that, update the following methods into your JWTAuthController.php file:

<?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:

 php artisan serve

Step 8: Now Test Laravel REST API in Postman

Here, you can see that, how to call laravel 8 restful API with jwt authentication:

Laravel Register Rest API :

laravel register api
laravel register api

Login API :

laravel passport login api
laravel login api

Next Step, you will call getUser API, In this API you have to set two headers follows:

 
Call login or register apis put $accessToken.

‘headers’ => [
‘Accept’ => ‘application/json’,
‘Authorization’ => ‘Bearer ‘.$accessToken,

]

Pass header in login/register rest API. it is necessary to jwt authentication in laravel app

Conclusion

Laravel 10 restful APIs with jwt auth tutorial, you have learned how to build rest APIs with jwt auth in Laravel 10 app. And as well as how to call this APIs on postman app.

Recommended Laravel Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *