API Development Authentication Backend Development Development Laravel Laravel 11 Laravel Security OAuth Tutorials

Implementing Laravel Passport Authentication in Laravel 11: A Complete Guide

Introduction

Laravel Passport provides a full OAuth2 server implementation for your Laravel applications in a matter of minutes. In this comprehensive guide, we’ll explore how to integrate and use Laravel Passport in Laravel 11 for secure API authentication.

Prerequisites

  • PHP 8.2 or higher
  • Composer installed
  • Laravel 11 application
  • Basic understanding of API authentication
  • MySQL or any compatible database

Table of Contents

  1. Installation and Setup
  2. Configuration
  3. Creating API Routes
  4. Generating Access Tokens
  5. Protecting Routes
  6. Best Practices
  7. Troubleshooting Common Issues

1. Installation and Setup

First, install Laravel Passport via Composer:

composer require laravel/passport

After installation, run the migration command

php artisan migrate

Install Passport:

php artisan passport:install

2. Configuration

Update User Model

Add the HasApiTokens trait to your User model:

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    // ...
}

Configure AuthServiceProvider

Update app/Providers/AuthServiceProvider.php:

use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        // ...
    ];

    public function boot(): void
    {
        $this->registerPolicies();
        
        Passport::tokensCan([
            'read-user' => 'Read user information',
            'write-user' => 'Modify user information',
        ]);
    }
}

Update config/auth.php

Modify the guards section:

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

3. Creating API Routes

Add these routes in routes/api.php:

Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);

Route::middleware('auth:api')->group(function () {
    Route::get('/user', [AuthController::class, 'user']);
    Route::post('/logout', [AuthController::class, 'logout']);
});

4. Authentication Controller

Create AuthController:

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if (!Auth::attempt($credentials)) {
            return response()->json([
                'message' => 'Invalid credentials'
            ], 401);
        }

        $user = Auth::user();
        $token = $user->createToken('AuthToken')->accessToken;

        return response()->json([
            'user' => $user,
            'access_token' => $token
        ]);
    }

    public function register(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => bcrypt($validated['password']),
        ]);

        $token = $user->createToken('AuthToken')->accessToken;

        return response()->json([
            'user' => $user,
            'access_token' => $token
        ], 201);
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }

    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }
}

5. Testing the Implementation

You can test your API endpoints using Postman or any API client:

Register a New User:

POST /api/register
{
    "name": "John Doe",
    "email": "[email protected]",
    "password": "password123",
    "password_confirmation": "password123"
}

Login

POST /api/login
{
    "email": "[email protected]",
    "password": "password123"
}

6. Best Practices

  1. Token Expiration: Set appropriate token expiration times
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
  1. Scope Implementation: Use scopes to limit access
Route::middleware(['auth:api', 'scope:read-user'])->get('/user', function () {
    // ...
});
  1. Error Handling: Implement proper error handling
try {
    // Your code
} catch (\Exception $e) {
    return response()->json([
        'error' => 'Authentication failed',
        'message' => $e->getMessage()
    ], 401);
}

7. Troubleshooting Common Issues

  1. Invalid Client Issue
    • Ensure you’ve run php artisan passport:install
    • Check if client IDs and secrets match
  2. Token Mismatch
    • Clear cache: php artisan cache:clear
    • Regenerate keys: php artisan passport:keys
  3. Migration Issues
    • Ensure all migrations are run
    • Check database configuration

Conclusion

Laravel Passport provides a robust OAuth2 server implementation for your Laravel 11 applications. By following this guide, you’ve learned how to implement secure API authentication using Passport, including setup, configuration, and best practices.

Leave a Comment

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

To top