Laravel 11 API Authentication using Laravel Passport

Websolutionstuff | Jun-28-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to API authentication in laravel 11 using a passport. Here, we'll use laravel passport and create a login and register API in laravel 11. Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

API stands for Application Program Interface, API is an interface that allows applications to exchange data.

Laravel 11 API Authentication using Laravel Passport

laravel 11 api authentication using laravel passport

 

Step 1: Install Laravel 11 Application

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

composer create-project laravel/laravel laravel-11-example

 

Step 2: Configure Database

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

.env

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

 

Step 3: Install Laravel API

Then, we'll install laravel API using the following command. In laravel by default API is not installed.

php artisan install:api

we'll update the authentication exception of our API middleware. 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

Then, we'll install the laravel passport composer package using the following command.

composer require laravel/passport

 

Step 5: Create Encryption Keys and Migrations

Now, we'll install a passport using the following command, create an encryption key, and create the necessary tables.

php artisan passport:install

Then, migrate the table into the database using the following command.

php artisan migrate

 

Step 6: Update User Model

Then, we'll update the user model and add the HasApiTokens.

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

Next, we'll update the AppServiceProvider to create our custom authentication. because we'll not use passport default routes.

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

Next, we'll define the driver in the auth.php file.

config/auth.php

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

 

Step 9: Create an Authentication Controller

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

php artisan make:controller Api/AuthenticationController

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: Define API routes

Then, define API routes into the api.php file

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');

 

Step 11: 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 Install Jenkins on Ubuntu
How to Install Jenkins on Ubun...

In today's fast-paced software development landscape, I've understood the significance of continuous integration...

Read More

Aug-07-2023

Laravel 11 Livewire Sweetalert Example
Laravel 11 Livewire Sweetalert...

Hello, laravel web developers! In this article, we'll see how to add sweetalert in laravel 11 Livewire. In laravel 1...

Read More

May-29-2024

Advanced Custom Error Handling and Logging Strategies in Laravel 11
Advanced Custom Error Handling...

Hello, laravel web developers! In this guide, I’ll walk you through setting up advanced error handling and logging...

Read More

Oct-04-2024

Laravel 8 Class NumberFormatter Not Found
Laravel 8 Class NumberFormatte...

In this example we will see example of laravel 8 class numberformatter not found. For numberformatter we need PHP 5...

Read More

Dec-27-2021