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
Carbon Add Minutes To Date In Laravel 9
Carbon Add Minutes To Date In...

In this article, we'll explore how to add minutes to a date in Laravel 8, Laravel 9 and Laravel 10 using Carbon...

Read More

Nov-23-2022

Laravel 8 Group By Query Example
Laravel 8 Group By Query Examp...

In this example we will see laravel 8 group by query example. how to use group by in laravel 8. As you might expect...

Read More

Nov-29-2021

Dependent Dropdown In Laravel 9 Vue JS
Dependent Dropdown In Laravel...

In this article, we will see a dependent dropdown in laravel 9 vue js. Here, we will learn how to create a dependent dro...

Read More

Dec-15-2022

Laravel 10 Delete Multiple Records Using Checkbox
Laravel 10 Delete Multiple Rec...

In this article, we will see laravel 10 delete multiple records using the checkbox. Here, we will learn about how to del...

Read More

Mar-03-2023