Laravel 11 JSON Web Token(JWT) Authentication

Websolutionstuff | Jul-10-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to authenticate using JWT in laravel 11. In laravel 11, we use JSON web token(JWT) for authentication. JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims.

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

JWT is commonly used for Authorization and Information Exchange.

How to Authenticate using JWT in Laravel 11

how to authenticate using JWT in laravel 11

 

Step1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following composer command.

composer create-project laravel/laravel laravel-11-jwt-auth

 

Step 2: Configure Database

Next, we'll configure the database to the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11_auth
DB_USERNAME=root
DB_PASSWORD=root

 

Step 3: Enable API and Update Authentication Exception

Then, we'll enable API routes. Because in laravel 11 by default API routes are not enabled.

php artisan install:api

bootstrap/app.php

<?php
 
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
 
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'message' => $e->getMessage(),
                ], 401);
            }
        });
    })->create();

 

Step 4: Install and Setup JWT Auth package

Now, install jwt-auth using the following composer command.

composer require php-open-source-saver/jwt-auth

Publish the config file.

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

Next, generate a secret key and add JWT config values on .env file.

php artisan jwt:secret

.env

JWT_SECRET=xxxxxxxx

config/auth.php

'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
 
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
 
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

 

Step 5: Update User Model

Next, we'll update the User.php file. Implement PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject contract on the User Model and also add getJWTIdentifier() and getJWTCustomClaims() methods.

app/Models/User.php

<?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 PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject; 
 
class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
 
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
 
    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
 
    /**
     * 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 6: Create the AuthController

Then, we'll create a controller using the following command.

php artisan make:controller AuthController

app/Http/Controllers/AuthController.php

<?php
  
namespace App\Http\Controllers;
  
use App\Http\Controllers\Controller;
use App\Models\User;
use Validator;
  
  
class AuthController extends Controller
{
 
    /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register() {
        $validator = Validator::make(request()->all(), [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ]);
  
        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }
  
        $user = new User;
        $user->name = request()->name;
        $user->email = request()->email;
        $user->password = bcrypt(request()->password);
        $user->save();
  
        return response()->json($user, 201);
    }
  
  
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);
  
        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
  
        return $this->respondWithToken($token);
    }
  
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }
  
    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();
  
        return response()->json(['message' => 'Successfully logged out']);
    }
  
    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }
  
    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

 

Step 7: Define Routes

Next, we'll define the routes into the api.php file

routes/api.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
 
Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('/register', [AuthController::class, 'register'])->name('register');
    Route::post('/login', [AuthController::class, 'login'])->name('login');
    Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api')->name('logout');
    Route::post('/refresh', [AuthController::class, 'refresh'])->middleware('auth:api')->name('refresh');
    Route::post('/me', [AuthController::class, 'me'])->middleware('auth:api')->name('me');
});

 

Step 8: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Create Dynamic Pie Chart In Laravel 9
How To Create Dynamic Pie Char...

In this article, we will see how to create a dynamic pie chart in laravel 9. Pie charts are used to repre...

Read More

Mar-20-2022

How to Change Date Format in Laravel 11
How to Change Date Format in L...

Hello developers! In this article, we'll see how to change the date format in laravel 11. Here, we'll learn...

Read More

Apr-29-2024

How to Handle Exception in PHP with Example
How to Handle Exception in PHP...

Hey there, Ever found yourself scratching your head over unexpected errors in your PHP code? Fret not, because today, we...

Read More

Dec-15-2023

Laravel 9 File Upload Example
Laravel 9 File Upload Example

In this artical, we will explain the laravel 9 file upload example step by step. As we know file upload is the most comm...

Read More

Mar-11-2022