Laravel 11 Passport API Authentication

Intorduction

Hi! Today, we will learn how to create authentication using Laravel Passport in our Laravel 11 API. Before diving in, let’s discuss what an API is and what Laravel Passport entails.

API stands for Application Programming Interface. It is an interface that allows applications to exchange data. In simpler terms, APIs are sets of functions that programmers can use to build software and applications.

Since our API is stateless and doesn’t have a session, we will be using Laravel Passport. Laravel Passport is an OAuth2 server that will be utilized for API authentication.

After installing laravel than:

Step 1: Enable API and Update Authentication Exception

By default, laravel 11 API route is not enabled in laravel 11. We will enable the API:

1php artisan install:api

After enabling the API, we will now update the authentication exception of our API middleware so that it will not redirect to login but will throw an exception:

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 2: Install Laravel Passport

Execute this command to install Passport:

1composer require laravel/passport

Step 5: Create Encryption Keys and Migrations

The Laravel passport has its database migrations directory. The passport migration will create tables to store clients and access tokens. let’s create the encryption keys for generating secure access tokens and run the migration. Run this command:

1php artisan passport:install

The command will create personal access and password grant to be used in generating access tokens.

Step 6: Update User Model

Add the Laravel\Passport\HasApiTokens trait to the App\Modles\User model. The trait provides helper methods for the model to inspect the authenticated user’s token and scopes.

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 Laravel\Passport\HasApiTokens;
 
class User extends Authenticatable
{
    use HasApiTokens, 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',
        ];
    }
}

Step 7: Update AppServiceProvider.php

We won’t be using the passport default routes, we will be creating our custom authentication so we will be removing the default routes. You can check the routes by executing this command: php artisan route:list.

app/Providers/AppServiceProvider.php

<?php
 
namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;
 
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        Passport::ignoreRoutes();
    }
 
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

Step 8: Set API Driver Option

The incoming API request will be authenticated by Passport’s TokenGuard.

config/auth.php

<?php
 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthenticationController;
 
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');
 
Route::post('register', [AuthenticationController::class, 'register'])->name('register');
Route::post('login', [AuthenticationController::class, 'login'])->name('login');