Day 6: Building APIs with Laravel Sanctum

day-6:-building-apis-with-laravel-sanctum

APIs are the backbone of modern applications, enabling seamless communication between different platforms. Laravel Sanctum provides a lightweight authentication system for securing APIs and building robust, scalable applications. In this blog, we’ll explore Sanctum, how to set it up, and its common use cases, including SPAs and token-based authentication.

What is Laravel Sanctum?

Laravel Sanctum is a simple package for API authentication that offers two main capabilities:

  • Token-based Authentication: Suitable for APIs accessed by third-party services or mobile apps.

  • Session-based Authentication: Ideal for single-page applications (SPAs) where the frontend and backend share the same domain.

Unlike heavier alternatives like Laravel Passport, Sanctum is lightweight, easy to configure, and tailored for applications that don’t require OAuth features.

Setting Up Laravel Sanctum

Step 1: Install Sanctum

To begin, install Sanctum via Composer:

composer require laravel/sanctum

Step 2: Publish Sanctum Configuration

Publish the Sanctum configuration file:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

This will create a config/sanctum.php file where you can customize Sanctum’s settings.

Step 3: Run Migrations

Sanctum uses a personal_access_tokens table to store issued tokens. Run the following command to create this table:

php artisan migrate

Step 4: Configure Middleware

Add Sanctum’s middleware to your api middleware group in app/Http/Kernel.php:

'api' => [
    LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    IlluminateRoutingMiddlewareSubstituteBindings::class,
],

Implementing Token-Based Authentication

Step 1: Protecting Routes

Define protected routes in your routes/api.php file. Use the auth:sanctum middleware to secure them:

use IlluminateSupportFacadesRoute;

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

Step 2: Generating Tokens

You can issue personal access tokens for a user using the createToken method:

use AppModelsUser;
use IlluminateHttpRequest;

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

Step 3: Revoking Tokens

Revoke a user’s token to log them out:

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

Use Case: Single-Page Applications (SPAs)

For SPAs, Sanctum uses session-based authentication. Here’s how to set it up:

Step 1: Enable CSRF Protection

Ensure Sanctum’s EnsureFrontendRequestsAreStateful middleware is correctly configured in api middleware.

Step 2: Configure Frontend

Make authenticated AJAX requests from your SPA by sending the CSRF token:

axios.defaults.withCredentials = true;

axios.get('/sanctum/csrf-cookie').then(() => {
    axios.post('/login', {
        email: 'example@example.com',
        password: 'password'
    });
});

Best Practices

  • Secure Your Tokens: Store tokens securely (e.g., in HTTP-only cookies) and avoid exposing them to client-side scripts.

  • Set Token Expiration: Use token expiration to minimize risks if a token is leaked.

  • Limit Token Scopes: Define specific scopes for tokens to restrict their permissions.

Conclusion

Laravel Sanctum makes it easy to secure APIs for modern applications. Whether you’re building a SPA or providing token-based access to third-party apps, Sanctum offers a powerful yet lightweight solution. With minimal configuration and a flexible API, Sanctum simplifies authentication for developers.

Feel free to try out Sanctum in your projects and explore its capabilities further!

Total
0
Shares
Leave a Reply

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

Previous Post
git

GIT

Next Post
.net-tarixi-haqida-qisqacha

.NET tarixi haqida qisqacha

Related Posts