Home >Backend Development >PHP Tutorial >Day Building APIs with Laravel Sanctum

Day Building APIs with Laravel Sanctum

Barbara Streisand
Barbara StreisandOriginal
2025-01-09 14:05:41870browse

Day Building APIs with Laravel Sanctum

Laravel Sanctum: A streamlined approach to API authentication in modern applications. APIs are crucial for inter-platform communication, and Sanctum offers a lightweight solution for securing them, fostering robust and scalable applications. This guide explores Sanctum's setup, features, and use cases, including SPAs and token-based authentication.

Understanding Laravel Sanctum

Laravel Sanctum simplifies API authentication, providing two key functionalities:

  • Token-based Authentication: Ideal for APIs accessed by external services or mobile applications.
  • Session-based Authentication: Best suited for single-page applications (SPAs) where the frontend and backend share the same domain.

Unlike more complex solutions, Sanctum's lightweight nature and straightforward configuration make it perfect for applications without OAuth requirements.

Implementing Laravel Sanctum

Step 1: Installation

Install Sanctum using Composer:

<code class="language-bash">composer require laravel/sanctum</code>

Step 2: Publishing Configuration

Publish the Sanctum configuration file:

<code class="language-bash">php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"</code>

This generates config/sanctum.php, allowing customization of Sanctum's settings.

Step 3: Database Migration

Sanctum utilizes a personal_access_tokens table. Create this table:

<code class="language-bash">php artisan migrate</code>

Step 4: Middleware Configuration

Integrate Sanctum's middleware into your api middleware group within app/Http/Kernel.php:

<code class="language-php">'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],</code>

Token-Based Authentication in Practice

Step 1: Route Protection

Secure routes in routes/api.php using the auth:sanctum middleware:

<code class="language-php">use Illuminate\Support\Facades\Route;

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

Step 2: Token Generation

Generate personal access tokens using the createToken method:

<code class="language-php">use App\Models\User;
use Illuminate\Http\Request;

Route::post('/login', function (Request $request) {
    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    return $user->createToken('auth_token')->plainTextToken;
});</code>

Step 3: Token Revocation

Revoke a user's token for logout:

<code class="language-php">Route::post('/logout', function (Request $request) {
    $request->user()->tokens()->delete();
    return response()->json(['message' => 'Logged out successfully']);
});</code>

Single-Page Application (SPA) Integration

Sanctum leverages session-based authentication for SPAs.

Step 1: CSRF Protection

Ensure EnsureFrontendRequestsAreStateful middleware is correctly configured within the api middleware group.

Step 2: Frontend Configuration

Send CSRF tokens with authenticated AJAX requests from your SPA:

<code class="language-bash">composer require laravel/sanctum</code>

Security Best Practices

  • Token Security: Store tokens securely (e.g., in HTTP-only cookies) and prevent client-side exposure.
  • Token Expiration: Implement token expiration to mitigate risks associated with leaked tokens.
  • Scope Limitation: Define specific scopes for tokens to control their permissions.

Conclusion

Laravel Sanctum offers a user-friendly and efficient way to secure APIs for modern applications. Its lightweight design and flexible API simplify authentication for developers, making it a valuable tool for both SPAs and token-based API access. Experiment with Sanctum in your projects to fully appreciate its capabilities.

The above is the detailed content of Day Building APIs with Laravel Sanctum. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn