LARAVEL

Laravel API Authentication: Complete Guide

January 20, 2024 18 min read

Introduction

Securing your Laravel API endpoints is crucial for protecting sensitive data and ensuring only authorized users can access your application's resources. Laravel provides multiple authentication mechanisms tailored for API development, including Laravel Sanctum, Laravel Passport, and JWT integration.

In this comprehensive guide, we'll explore each authentication method, their use cases, and how to implement them effectively in your Laravel applications.

Laravel Authentication Overview

Laravel offers several authentication options for APIs:

  • Laravel Sanctum - Lightweight token-based authentication for SPAs and mobile apps
  • Laravel Passport - Full OAuth2 server implementation
  • JWT (JSON Web Tokens) - Stateless authentication using tokens
  • API Tokens - Simple token-based authentication

Laravel Sanctum

Laravel Sanctum provides a simple, lightweight solution for API token authentication. It's perfect for single-page applications (SPAs) and mobile applications.

Installation

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Configuration

// config/auth.php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'sanctum' => [
        'driver' => 'sanctum',
        'provider' => 'users',
    ],
],

Creating API Tokens

// In User model
use Laravel\Sanctum\HasApiTokens;

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

// Create token for user
$token = $user->createToken('api-token')->plainTextToken;

Authenticating Requests

// Using Authorization header
Authorization: Bearer 1|AbCdEfGhIjKlMnOpQrStUvWxYz1234567890

Laravel Passport

Laravel Passport provides a full OAuth2 server implementation for your Laravel application. It's ideal when you need to support third-party applications or complex authorization flows.

Installation

composer require laravel/passport
php artisan passport:install

Configuration

// config/auth.php
'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Defining Scopes

// App\Providers\AuthServiceProvider
use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();
    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);
}

OAuth2 Flow

// Authorization URL
GET /oauth/authorize
    ?client_id={client_id}
    &redirect_uri={redirect_uri}
    &response_type=code
    &scope={scope}

// Token request
POST /oauth/token
grant_type=authorization_code
&code={code}
&client_id={client_id}
&client_secret={client_secret}
&redirect_uri={redirect_uri}

JWT Authentication

JWT (JSON Web Tokens) provide stateless authentication that's popular for mobile apps and microservices architectures.

Installation

composer require php-open-source-saver/jwt-auth
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret

Configuration

// config/auth.php
'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

User Model

use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

Authentication Controller

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

    if (!$token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return $this->respondWithToken($token);
}

protected function respondWithToken($token)
{
    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth()->factory()->getTTL() * 60
    ]);
}

API Guards & Middleware

Laravel's middleware system provides fine-grained control over API access.

Route Protection

// Using auth middleware
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
});

// Using auth:api guard
Route::middleware('auth:api')->get('/profile', function ($request) {
    return $request->user();
});

Custom Middleware

php artisan make:middleware CheckApiKey

// In middleware
public function handle($request, Closure $next)
{
    $apiKey = $request->header('X-API-KEY');
    
    if (!$apiKey || $apiKey !== config('services.api.key')) {
        return response()->json(['error' => 'Invalid API key'], 401);
    }
    
    return $next($request);
}

Best Practices

  • Use HTTPS always - Never transmit tokens over unencrypted connections
  • Implement token expiration - Short-lived access tokens with refresh tokens
  • Store tokens securely - Use secure storage in mobile apps, httpOnly cookies for SPAs
  • Implement rate limiting - Protect against brute force attacks
  • Use scopes/permissions - Limit token capabilities to necessary permissions only
  • Log authentication events - Track login attempts and token usage
  • Implement token revocation - Allow users to logout and invalidate tokens

Summary

Laravel provides robust authentication mechanisms for APIs. Choose Laravel Sanctum for simple SPA and mobile app authentication, Laravel Passport for full OAuth2 implementations, or JWT for stateless token-based authentication.

For more Laravel tutorials, check out our guide on Laravel Performance Optimization and Laravel Security Best Practices.