Laravel 12 with Laravel Passport for API Authentication

Hi there! I’m excited to share my journey of setting up secure API authentication using Laravel 12 and Laravel Passport. If you’re a developer looking to build robust APIs, Laravel 12 makes it super easy with its elegant syntax and powerful tools.

Laravel Passport, an OAuth2 server implementation, simplifies token-based authentication, ensuring your APIs are secure and scalable.

In this guide, I’ll walk you through the process step-by-step, sharing practical tips and code snippets to help you master Laravel 12 authentication.

Why Choose Laravel Passport for API Authentication?

Before we get started, let’s talk about why Laravel Passport is a great choice for Laravel 12 authentication:

  • OAuth2 Compliance: Follows industry-standard OAuth2 for secure token-based authentication.
  • Simplified Token Management: Easily issue, refresh, and revoke access tokens.
  • Scalability: Integrates seamlessly with Laravel’s ecosystem, perfect for small to large apps.
  • Comprehensive Features: Supports personal access tokens, client credentials, and more.

This article will guide you through setting up Laravel Passport, securing API routes, and managing tokens effectively, all while focusing on Laravel 12 authentication.

Step-by-Step Guide to Implementing Laravel Passport in Laravel 12

Laravel 12 with Laravel Passport for API Authentication

 

Here’s a detailed, beginner-friendly guide to setting up API authentication in Laravel 12 using Laravel Passport. Follow along, and you’ll have a secure API in no time!

 

Step 1: Set Up a Laravel 12 Project

First, ensure you have Composer installed. Then, create a new Laravel 12 project:

composer create-project --prefer-dist laravel/laravel laravel-passport-auth
cd laravel-passport-auth

Configure your database in the .env file:

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

Run migrations to set up the default database tables:

php artisan migrate

 

Step 2: Install Laravel Passport

Install Laravel Passport using Composer:

composer require laravel/passport

Next, run the install:api Artisan command to publish Passport’s migrations and generate encryption keys:

php artisan install:api

This command creates tables for OAuth2 clients and tokens and generates oauth-public.key and oauth-private.key for secure token issuance.

 

Step 3: Configure the User Model

Add the HasApiTokens trait to your User model (app/Models/User.php) to enable token management:

<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = ['name', 'email', 'password'];
}

 

Step 4: Set Up Authentication Guard

Update the config/auth.php file to use Passport’s TokenGuard for API authentication:

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

 

Step 5: Create Authentication Routes

Let’s create a custom AuthController to handle registration and login. Generate the controller:

php artisan make:controller AuthController

Add the following code to app/Http/Controllers/AuthController.php:

<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    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',
        ]);

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

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

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

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

        if (auth()->attempt($credentials)) {
            $token = auth()->user()->createToken('auth_token')->accessToken;
            return response()->json(['token' => $token], 200);
        }

        return response()->json(['error' => 'Unauthorized'], 401);
    }
}

Define API routes in routes/api.php:

<?php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

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

Route::middleware('auth:api')->group(function () {
    Route::get('/user', function () {
        return auth()->user();
    });
});

 

Step 6: Secure API Routes

The auth:api middleware protects routes, ensuring only authenticated users with valid tokens can access them. Test the /user route by sending a GET request with the Authorization: Bearer <token> header.

 

Step 7: Test the API

Use a tool like Postman to test your API:

  1. Register: Send a POST request to /api/register with name, email, and password.
  2. Login: Send a POST request to /api/login with email and password.
  3. Access Protected Route: Send a GET request to /api/user with the token in the Authorization header.

Example Postman request for login:

  • URL: http://localhost:8000/api/login
  • Method: POST
  • Body (JSON):
    {
        "email": "[email protected]",
        "password": "password123"
    }
    

You’ll receive a JSON response with an access token if successful.

 

Step 8: Token Management

Laravel Passport supports token revocation and refresh tokens. To revoke a token (e.g., for logout), add a logout method to AuthController:

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

Add the route in routes/api.php:

Route::middleware('auth:api')->post('/logout', [AuthController::class, 'logout']);

 

Best Practices for Laravel 12 Authentication

  • Use HTTPS: Ensure your API runs over HTTPS to encrypt token transmission.
  • Limit Token Scopes: Define scopes to restrict token access to specific resources.
  • Rotate Encryption Keys: Periodically update oauth-public.key and oauth-private.key.
  • Validate Inputs: Always validate user inputs to prevent security vulnerabilities.
  • Rate Limiting: Apply Laravel’s rate-limiting middleware to protect against brute-force attacks.

 

Conclusion

Setting up API authentication in Laravel 12 with Laravel Passport is straightforward and powerful. By following this guide, you’ve learned how to install Passport, configure your application, secure API routes, and manage tokens effectively.

Laravel 12 authentication with Passport ensures your APIs are secure, scalable, and compliant with OAuth2 standards. Whether you’re building a mobile app or a web platform, Passport simplifies the process, letting you focus on creating amazing features. Start implementing these steps today, and take your Laravel development to the next level!

 

Frequently Asked Questions (FAQs)

  1. What is Laravel Passport?

    Laravel Passport is an OAuth2 server implementation for Laravel. It enables secure, token-based API authentication and simplifies access token management.

  2. Why use Laravel Passport instead of Laravel Sanctum?

    Passport is ideal for full OAuth2 support in complex APIs. Sanctum is simpler and better suited for SPAs or mobile apps needing basic token auth.

  3. How do I refresh tokens in Laravel Passport?

    Use the refresh_token grant type. Send a POST request to /oauth/token with the necessary parameters to obtain a new access token.

  4. Can I use Laravel Passport with Laravel 12?

    Yes, Laravel Passport is fully compatible with Laravel 12 and provides advanced API authentication tools out of the box.

  5. How do I secure my Laravel 12 API?

    Use auth:api middleware, enforce HTTPS, validate all input, limit token scopes, and apply throttle middleware to reduce abuse.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS