Laravel 12 API Authentication using Laravel Passport

Laravel 12 API Authentication using Laravel Passport

Introduction:

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

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:

Before we proceed we must update the composerlaravel installernode, and npm on our local environment:

  • PHP >= 8.2
  • Node >= 18.18.2
  • NPM >= 9.8.1
  • Composer >= 2.8.6
  • Laravel Installer >= 5.12.2

If you are having trouble updating the Composer follow these steps:

composer self-update

If you are having trouble updating the Laravel Installer, follow these steps:

composer global remove laravel/installer
composer global update
composer global require laravel/installer

Step 1: Install Laravel 12 Using Composer

Run this command on Terminal or CMD to install Laravel:

laravel new laravel-12-passport

Follow these choices:

image 87 Binaryboxtuts
image 93 Binaryboxtuts

Step 2: Set Database Configuration

We set up the database configuration during our installation. We can change it by going inside the project root folder, opening the file .env and put the configuration for the database.

.env

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

Step 3: Enable API and Install Passport

By default, laravel 12 API route is not enabled in laravel 12. We will enable the API and install Passport :

php artisan install:api --passport

Step 4: 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 5: 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 6: 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 7: 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 8: Create API routes

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

routes/api.php

&lt;?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.

Leave a Reply

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