Laravel 11 API Authentication using Laravel Passport

Laravel 11 API Authentication using Laravel Passport

Avatar photoPosted by

Introduction:

Hi! Today we will learn how to create an authentication using laravel passport on our Laravel 11 API. But before that let has a discussion about API and what is Laravel Passport.

API stands for Application Program Interface, API is an interface that allows applications to exchange data. To make it more clear, APIs are a set of functions that can be used by programmers to build software and applications.

Since our API is stateless and doesn’t have a session we will be using the Laravel Passport. It is an Oauth2 server that will be used for API authentication.

Prerequisite:

Step 1: Install Laravel 11 Using Composer

First, select a folder that you want the Laravel to be installed then execute this command on Terminal or CMD to install Laravel 11:

 composer create-project laravel/laravel laravel-11-passport

Install via Laravel Installer:

laravel new laravel-11-passport

Step 2: Set Database Configuration

Open the .env file and set the database configuration:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name(laravel_11_passport)
DB_USERNAME=your database username(root)
DB_PASSWORD=your database password(root)

Step 3: Enable API and Update Authentication Exception

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

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

Execute this command to install Passport:

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

php 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

  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

Step 9: Create an Authentication Controller

Now, Let’s create a controller that will be responsible for registering and authenticating users. Run this command:

php artisan make:controller Api/AuthenticationController

then open the AuthenticationController file, and add these codes:

app/Http/Controllers/Api/AuthenticationController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
 
 
class AuthenticationController extends Controller
{
    public function register(Request $request)
    {
        $formData = [
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
        ];
 
        $formData['password'] = bcrypt($request->password);
 
        $user = User::create($formData);        
 
        return response()->json([ 
            'user' => $user, 
            'token' => $user->createToken('passportToken')->accessToken
        ], 200);
         
    }
 
    public function login(Request $request)
    {
        $credentials = [
            'email'    => $request->email,
            'password' => $request->password
        ];
 
        if (Auth::attempt($credentials)) 
        {
            $token = Auth::user()->createToken('passportToken')->accessToken;
            
            return response()->json([
                'user' => Auth::user(), 
                'token' => $token
            ], 200);
        }
 
        return response()->json([
            'error' => 'Unauthorised'
        ], 401);
 
    }
}

Step 10: Create API routes

Finally, let’s create a route for the user to register and login.

routes/api.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');

Let’s test the API Authentication

We will be using Postman for our testing, but you can test it in the way you prefer.

Register

image Binaryboxtuts

Login

image 1 Binaryboxtuts

The access token will be used when accessing an API route that needs authentication. Try accessing the /api/user route.

image 2 Binaryboxtuts

Now our API authentication is done.