laravel-sanctum

Auto-invoked skill

Implement API token and SPA authentication

Trigger Keywords

This skill automatically activates when Claude detects these keywords:

sanctum api token spa auth bearer token personal access token mobile auth

Overview

The laravel-sanctum skill provides expertise for lightweight API authentication. It covers API token generation, SPA authentication, token abilities/scopes, and mobile app authentication.

What This Skill Provides

  • API Tokens - Personal access token generation
  • SPA Authentication - Session-based auth for SPAs
  • Token Abilities - Scope-based permissions
  • Mobile Auth - Token auth for mobile apps
  • Token Management - Revoke and refresh tokens

Quick Start

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

User Model Setup

<?php

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
}

Issuing Tokens

// Create token with abilities
$token = $user->createToken(
    'api-token',
    ['posts:read', 'posts:write']
);

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

Protecting Routes

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

Token Abilities

// Check ability
if ($request->user()->tokenCan('posts:write')) {
    // Can write posts
}

// Middleware
Route::middleware(['auth:sanctum', 'abilities:posts:read'])->get('/posts');

// Create with abilities
$token = $user->createToken('admin', ['*']); // All abilities

SPA Configuration

// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS',
    'localhost,localhost:3000,127.0.0.1'
)),

// config/cors.php
'supports_credentials' => true,
// Frontend SPA
await axios.get('/sanctum/csrf-cookie');
await axios.post('/login', credentials);
// Now authenticated via session

Revoking Tokens

// Revoke current token
$request->user()->currentAccessToken()->delete();

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

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

Testing

use Laravel\Sanctum\Sanctum;

it('authenticates with token', function () {
    $user = User::factory()->create();

    Sanctum::actingAs($user, ['posts:read']);

    $response = $this->getJson('/api/posts');

    $response->assertOk();
});

Common Pitfalls

  • Missing HasApiTokens trait - Add to User model
  • CORS issues with SPA - Set supports_credentials => true
  • Storing plain text token - Only available at creation time
  • Not checking abilities - Always validate token permissions
  • Missing CSRF cookie - SPA must request it first

Best Practices

  • Use abilities to scope token permissions
  • Set token expiration for security
  • Revoke tokens on password change
  • Use device names to identify tokens
  • Rate limit authentication endpoints
  • Use HTTPS in production

Related Skills