Logo

dev-resources.site

for different kinds of informations.

Day 6: Building APIs with Laravel Sanctum

Published at
1/9/2025
Categories
laravel
php
api
tutorial
Author
ehtesham_ali_abc367f36a5b
Categories
4 categories in total
laravel
open
php
open
api
open
tutorial
open
Author
25 person written this
ehtesham_ali_abc367f36a5b
open
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
Enter fullscreen mode Exit fullscreen mode

Step 2: Publish Sanctum Configuration

Publish the Sanctum configuration file:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Middleware

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

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Enter fullscreen mode Exit fullscreen mode

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 Illuminate\Support\Facades\Route;

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

Step 2: Generating Tokens

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

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;
});
Enter fullscreen mode Exit fullscreen mode

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']);
});
Enter fullscreen mode Exit fullscreen mode

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: '[email protected]',
        password: 'password'
    });
});
Enter fullscreen mode Exit fullscreen mode

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!

laravel Article's
30 articles in total
Favicon
Serve a Laravel project on Web, Desktop and Mobile with Tauri
Favicon
Host Header Injection in Laravel: Risks and Prevention
Favicon
Laravel 11.30: A Leap Forward in Testing, Model IDs, and Authorization
Favicon
How to Effectively Manage Laravel Request Validation?
Favicon
[Boost]
Favicon
Building a Quick CSV Export Command in Laravel
Favicon
Deploy laravel application using vercel : Amazing
Favicon
How to Image Upload with CKeditor in Laravel 11 Tutorial
Favicon
How to Install and Use Trix Editor in Laravel 11
Favicon
Testing Temporary URLs in Laravel Storage
Favicon
API Vulnerabilities in Laravel: Identify & Secure Your Endpoints
Favicon
Enforcing Strong Passwords in Laravel
Favicon
Beyond MVC: Redefining Backend Development with DataForge
Favicon
From Product Manager to Independent Developer: A Six-Month Transformation Guide
Favicon
"PHP is dead⚰️" .. what's next? Is Laravel worth it? 😎
Favicon
LTS as a Business: How an Old Project Can Become the Foundation for a New Business Model
Favicon
How to Fix the "PHP Not Found" Error on macOS After Installing XAMPP
Favicon
Sending logs to Telegram. Module for Laravel
Favicon
Need someone to contribute in writing test code for my open source project
Favicon
6 Steps to Master PHPUnit Testing with Ease!
Favicon
How to Create a Reusable Laravel Admin Panel for Multiple Projects
Favicon
Day 6: Building APIs with Laravel Sanctum
Favicon
Fix Insufficient Logging & Monitoring in Laravel Easily
Favicon
πŸŽ‰ Simplify Laravel CRUD Operations with Ease! πŸš€
Favicon
Laravel IQ - Level 1 - Part 2
Favicon
Different ways to use where() in Laravel
Favicon
Laravel IQ - Level 1 - Part 1
Favicon
Leveraging Social Media to Attract Top PHP Developers
Favicon
Laravel Eloquent ORM in Bangla Part-3 (Models Retrieving)
Favicon
How to Build a Generic CRUD Controller in Laravel for Multiple Resources

Featured ones: