Laravel Sanctum API Authentication: Step-by-Step Tutorial (2026)

By Lyndon Bermoy

Updated on:

Laravel Sanctum API Authentication: Step-by-Step Tutorial (2026)

Laravel Sanctum provides a lightweight API authentication system for single-page applications, mobile apps, and simple token-based APIs. It is included in Laravel by default and requires minimal configuration compared to JWT or OAuth 2.0. This tutorial builds a complete authenticated API from scratch.

What Sanctum Provides

  • API tokens — issue tokens for mobile apps and third-party integrations
  • SPA authentication — cookie-based authentication for same-domain SPAs (React, Vue)
  • Token scopes — limit what each token can do
  • Token revocation — invalidate individual tokens or all tokens for a user

Step 1: Install Sanctum

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
# This creates the personal_access_tokens table

Step 2: Configure the User Model

// app/Models/User.php
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable {
    use HasApiTokens, HasFactory, Notifiable;
    // ...
}

Step 3: Create Authentication Routes

// routes/api.php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

// Public routes (no authentication required):
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login',    [AuthController::class, 'login']);

// Protected routes (require valid Sanctum token):
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user',          [AuthController::class, 'user']);
    Route::post('/logout',       [AuthController::class, 'logout']);
    Route::get('/profile',       [ProfileController::class, 'show']);
    Route::put('/profile',       [ProfileController::class, 'update']);
    Route::apiResource('posts',  PostController::class);
});

Step 4: Build the Auth Controller

// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller {

    public function register(Request $request): JsonResponse {
        $data = $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user  = User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'user'  => $user->only('id', 'name', 'email'),
            'token' => $token,
        ], 201);
    }

    public function login(Request $request): JsonResponse {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        // Revoke previous tokens (optional — one active token per device):
        // $user->tokens()->delete();

        $token = $user->createToken($request->device_name ?? 'api')->plainTextToken;

        return response()->json([
            'user'  => $user->only('id', 'name', 'email'),
            'token' => $token,
        ]);
    }

    public function user(Request $request): JsonResponse {
        return response()->json($request->user()->only('id', 'name', 'email'));
    }

    public function logout(Request $request): JsonResponse {
        // Revoke the current token:
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out successfully']);
    }
}

Step 5: Using the API from a Client

# Register:
curl -X POST https://api.yourapp.com/api/register \
  -H "Content-Type: application/json" \
  -d '{"name":"Lyndon","email":"lyndon@example.com","password":"secret123","password_confirmation":"secret123"}'
# Response: {"user":{...},"token":"1|abcdefgh..."}

# Login:
curl -X POST https://api.yourapp.com/api/login \
  -H "Content-Type: application/json" \
  -d '{"email":"lyndon@example.com","password":"secret123"}'

# Access protected route (use the token from login):
curl https://api.yourapp.com/api/user \
  -H "Authorization: Bearer 1|abcdefgh..."
  -H "Accept: application/json"

Token Scopes

// Issue token with specific abilities (scopes):
$token = $user->createToken('mobile-app', ['posts:read', 'posts:create'])->plainTextToken;

// Check ability in a controller:
if (!$request->user()->tokenCan('posts:create')) {
    return response()->json(['error' => 'Insufficient permissions'], 403);
}

// Or use middleware:
Route::post('/posts', [PostController::class, 'store'])
    ->middleware(['auth:sanctum', 'ability:posts:create']);

Token Management

// List all tokens for the authenticated user:
$tokens = $request->user()->tokens;

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

// Revoke all tokens (force logout from all devices):
$request->user()->tokens()->delete();

// Set token expiration in config/sanctum.php:
// 'expiration' => 60 * 24 * 7, // 7 days in minutes (null = never expires)

Frequently Asked Questions

When should I use Sanctum vs Passport?

Use Sanctum for most applications — it handles token-based auth for mobile apps, SPAs, and simple APIs with minimal setup. Use Passport when you need full OAuth 2.0 features (authorization code flow, client credentials, refresh tokens) for third-party app integrations. Sanctum covers 90% of API authentication requirements with a fraction of the complexity.

READ ALSO:   How to Use Debugging in a Real Project

How do I handle token refresh in Sanctum?

Sanctum does not have built-in token refresh like JWT. The common approach: set an expiration on tokens (config/sanctum.php → 'expiration'), and have the client re-authenticate when they receive a 401. For long-lived sessions, issue tokens with no expiration and let users manage them.

Conclusion

Laravel Sanctum is the right choice for API authentication in the vast majority of Laravel applications. Installation takes 3 minutes, the auth controller pattern shown above covers register/login/logout, and token scopes handle permission-based access. For mobile apps, issue one token per device; for web SPAs on the same domain, use Sanctum’s cookie-based SPA authentication instead of tokens.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment