Skip to main content

Command Palette

Search for a command to run...

Laravel Sanctum: A Comprehensive Guide

Published
4 min read

Laravel Sanctum is a lightweight authentication package designed for single-page applications (SPAs), mobile applications, and simple token-based APIs. It provides a straightforward way to authenticate users via API tokens without the complexity of OAuth.


Key Features of Laravel Sanctum

1. API Token Authentication

Sanctum allows applications to issue API tokens for users. These tokens can be granted specific abilities or permissions.

2. SPA Authentication

Sanctum provides a simple way to authenticate SPAs using Laravel's built-in session-based authentication system.

3. Token Scopes

Tokens issued by Sanctum can have abilities (or scopes) that define what actions the token is allowed to perform.

4. CSRF Protection

For SPAs, Sanctum handles Cross-Site Request Forgery (CSRF) protection out of the box by leveraging Laravel's session cookies.

5. Easy Integration

Sanctum is easy to set up and integrates seamlessly with Laravel's authentication system, making it an excellent choice for developers looking for simplicity and security.


Installing Laravel Sanctum

Follow these steps to install and configure Sanctum:

  1. Install Sanctum via Composer:

    composer require laravel/sanctum
    
  2. Publish Sanctum's Configuration File:

    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
    

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

  3. Run Migrations: Sanctum requires a database table to store API tokens. Run the following command to create the table:

    php artisan migrate
    
  4. Add Middleware: To enable Sanctum's session-based authentication, add the EnsureFrontendRequestsAreStateful 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,
    ],
    

Using Laravel Sanctum

1. Issuing API Tokens

To issue tokens, use the createToken method provided by the HasApiTokens trait:

use Illuminate\Support\Facades\Auth;

$user = Auth::user();
$token = $user->createToken('auth-token')->plainTextToken;

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

You can also specify abilities for the token:

$token = $user->createToken('auth-token', ['create-posts', 'edit-posts'])->plainTextToken;
return response()->json(['token' => $token]);

2. Protecting Routes

Sanctum provides the auth:sanctum middleware to protect your API routes. Add it to the desired routes:

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

Example:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::post('/posts', [PostController::class, 'store']);
    Route::delete('/posts/{id}', [PostController::class, 'destroy']);
});

3. Token Abilities

You can assign specific abilities to tokens during creation:

$token = $user->createToken('auth-token', ['view-posts', 'edit-posts'])->plainTextToken;

To check abilities, use the tokenCan method:

if ($request->user()->tokenCan('edit-posts')) {
    // The token has the 'edit-posts' ability.
    return response()->json(['message' => 'Token can edit posts']);
}

4. Authenticating SPAs

For SPAs, Sanctum uses cookies for authentication. Follow these steps:

  • Set Up CSRF Protection: Include the CSRF token in your requests:

    axios.get('/sanctum/csrf-cookie').then(response => {
        // Now you can authenticate the user.
    });
    
  • Log in the User: Use Laravel's built-in login route or create your own:

    axios.post('/login', {
        email: 'user@example.com',
        password: 'password',
    }).then(response => {
        // User is authenticated.
    });
    
  • Example SPA Workflow:

    1. Make a GET request to /sanctum/csrf-cookie to set the CSRF token.
    2. Log in the user by sending credentials to the /login endpoint.
    3. Use Axios or another HTTP client to make authenticated requests by including the session cookie.

Configuration Options

The config/sanctum.php file contains various options to customize Sanctum’s behavior. Key options include:

  • Stateful Domains: Define which domains should receive stateful authentication cookies:

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,example.com')),
    
  • Token Expiration: Set token expiration time:

    'expiration' => 60, // in minutes
    
  • Middleware: Configure middleware for stateful and API authentication.


Advanced Examples

Revoking Tokens

Users can revoke their tokens by deleting them from the database:

$user->tokens()->delete(); // Revoke all tokens

$user->tokens()->where('id', $tokenId)->delete(); // Revoke a specific token

Listing Active Tokens

You can list all active tokens for a user:

$tokens = $user->tokens;
foreach ($tokens as $token) {
    echo $token->name;
}

Custom Middleware for Abilities

You can create custom middleware to handle token abilities:

php artisan make:middleware CheckAbility

In the middleware:

public function handle($request, Closure $next, $ability)
{
    if (!$request->user()->tokenCan($ability)) {
        return response()->json(['error' => 'Unauthorized'], 403);
    }

    return $next($request);
}

Apply the middleware to a route:

Route::middleware(['auth:sanctum', 'ability:view-posts'])->get('/posts', [PostController::class, 'index']);

Best Practices

  1. Use HTTPS: Always use HTTPS in production to secure token transmission.
  2. Limit Token Abilities: Assign only the necessary abilities to tokens to minimize security risks.
  3. Set Token Expiration: Configure a reasonable expiration time for tokens to reduce misuse.
  4. Revoke Tokens: Provide users with the ability to revoke tokens if they suspect misuse.
  5. Monitor Token Usage: Track token usage and investigate suspicious activities.

Common Use Cases

  1. API Authentication: Sanctum is ideal for securing RESTful APIs with minimal setup.
  2. SPA Authentication: Use Sanctum to authenticate SPAs using cookies and CSRF protection.
  3. Mobile App Authentication: Issue API tokens for mobile applications to authenticate users securely.

Conclusion

Laravel Sanctum is a versatile and lightweight solution for API authentication. Its ease of use and seamless integration with Laravel's authentication system make it an excellent choice for SPAs, mobile applications, and APIs. By leveraging its features, developers can build secure, scalable, and maintainable authentication systems for modern web and mobile applications.

More from this blog

Khang Nguyen

119 posts