Bird
Raised Fist0
Laravelframework~5 mins

API authentication with Sanctum in Laravel

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

API authentication with Sanctum helps your app know who is using it safely. It keeps private data secure by checking user identity.

When building a mobile app that talks to your Laravel backend.
When you want users to log in and access their own data via API.
When you need simple token-based authentication without complex OAuth.
When you want to protect routes so only logged-in users can use them.
When you want to manage API tokens easily for users.
Syntax
Laravel
1. Install Sanctum via Composer:
   composer require laravel/sanctum

2. Publish Sanctum config and migration:
   php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

3. Run migrations:
   php artisan migrate

4. Add Sanctum middleware in api middleware group in app/Http/Kernel.php:
   'api' => [
       \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
       'throttle:api',
       \Illuminate\Routing\Middleware\SubstituteBindings::class,
   ],

5. Use HasApiTokens trait in User model:
   use Laravel\Sanctum\HasApiTokens;

6. Issue tokens in controller:
   $token = $user->createToken('token-name')->plainTextToken;

7. Protect routes with 'auth:sanctum' middleware.

Sanctum uses simple API tokens or SPA authentication.

Tokens are stored securely and can be revoked anytime.

Examples
Adds token abilities to the User model.
Laravel
<?php
// In User.php model
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Creates a new API token for the user and returns it.
Laravel
<?php
// In controller to create token
$token = $user->createToken('mobile-app')->plainTextToken;
return ['token' => $token];
Only authenticated users with valid tokens can access this route.
Laravel
// Protect API route in routes/api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Sample Program

This example shows how to register and login users to get API tokens. The /profile route is protected and returns user info only if the token is valid.

Laravel
<?php
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Support\Facades\Route;

// Register user and return token
Route::post('/register', function (Request $request) {
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);
    $token = $user->createToken('api-token')->plainTextToken;
    return ['token' => $token];
});

// Login user and return token
Route::post('/login', function (Request $request) {
    $user = User::where('email', $request->email)->first();
    if (! $user || ! Hash::check($request->password, $user->password)) {
        return response(['message' => 'Invalid credentials'], 401);
    }
    $token = $user->createToken('api-token')->plainTextToken;
    return ['token' => $token];
});

// Protected route
Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});
OutputSuccess
Important Notes

Always protect sensitive routes with 'auth:sanctum' middleware.

Tokens can be revoked by deleting them from the database.

Use HTTPS to keep tokens safe during transmission.

Summary

Sanctum provides simple API token authentication for Laravel apps.

Use HasApiTokens trait and createToken() to issue tokens.

Protect routes with 'auth:sanctum' middleware to require login.

Practice

(1/5)
1. What is the main purpose of Laravel Sanctum in API development?
easy
A. To handle frontend routing in Laravel apps
B. To provide simple token-based API authentication
C. To manage database migrations automatically
D. To optimize SQL queries for performance

Solution

  1. Step 1: Understand Sanctum's role

    Sanctum is designed to provide a simple way to authenticate API requests using tokens.
  2. Step 2: Compare options

    The incorrect options relate to frontend routing, database migrations, and SQL query optimization, which are other Laravel features, not Sanctum's main purpose.
  3. Final Answer:

    To provide simple token-based API authentication -> Option B
  4. Quick Check:

    Sanctum = API token authentication [OK]
Hint: Sanctum = simple API token auth [OK]
Common Mistakes:
  • Confusing Sanctum with database or routing features
  • Thinking Sanctum manages frontend or SQL optimization
2. Which of the following is the correct way to protect an API route using Sanctum middleware in Laravel?
easy
A. Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); });
B. Route::middleware('api')->get('/user', function () { return auth()->user(); });
C. Route::middleware('sanctum')->get('/user', function () { return auth()->user(); });
D. Route::middleware('auth')->get('/user', function () { return auth()->user(); });

Solution

  1. Step 1: Identify Sanctum middleware syntax

    Sanctum uses 'auth:sanctum' middleware to protect routes requiring token authentication.
  2. Step 2: Check each option

    Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); }); uses 'auth:sanctum' correctly; others use incorrect or incomplete middleware names.
  3. Final Answer:

    Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); }); -> Option A
  4. Quick Check:

    Sanctum middleware = 'auth:sanctum' [OK]
Hint: Use 'auth:sanctum' middleware to protect API routes [OK]
Common Mistakes:
  • Using 'auth' instead of 'auth:sanctum'
  • Omitting middleware or using wrong names like 'sanctum' alone
  • Confusing 'api' middleware with Sanctum middleware
3. Given this code snippet, what will be the output when a valid token is used to access the route?
use Illuminate\Http\Request;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user()->name;
});
medium
A. The name of the authenticated user
B. An error: Method user() does not exist
C. Null, because user() returns nothing
D. The user's email address

Solution

  1. Step 1: Understand the middleware effect

    The 'auth:sanctum' middleware ensures the request is authenticated and $request->user() returns the authenticated user model.
  2. Step 2: Analyze the return statement

    The code returns $request->user()->name, which outputs the authenticated user's name.
  3. Final Answer:

    The name of the authenticated user -> Option A
  4. Quick Check:

    $request->user()->name = user name [OK]
Hint: auth:sanctum gives user() object; name property outputs user name [OK]
Common Mistakes:
  • Assuming user() returns null or causes error
  • Confusing user name with email
  • Ignoring middleware authentication effect
4. Identify the error in this code snippet for issuing a Sanctum API token:
use App\Models\User;

$user = User::find(1);
$token = $user->createToken;
return $token->plainTextToken;
medium
A. User model does not support createToken method
B. User::find(1) returns null causing error
C. plainTextToken is not a valid property
D. Missing parentheses when calling createToken() method

Solution

  1. Step 1: Check method call syntax

    The createToken method must be called with parentheses and a token name string, e.g. createToken('token-name').
  2. Step 2: Analyze given code

    The code uses $user->createToken without parentheses, so it references the method, not calls it, causing an error.
  3. Final Answer:

    Missing parentheses when calling createToken() method -> Option D
  4. Quick Check:

    Method calls need parentheses () [OK]
Hint: Always call createToken() with parentheses and token name [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Not passing token name string to createToken()
  • Assuming plainTextToken is invalid
5. You want to issue a token for a user and restrict it to only allow access to 'orders' and 'products' API scopes. Which code snippet correctly creates this token with scopes using Laravel Sanctum?
hard
A. $token = $user->createToken('api-token', 'orders', 'products');
B. $token = $user->createToken('api-token')->scopes(['orders', 'products']);
C. $token = $user->createToken('api-token', ['orders', 'products']);
D. $token = $user->createToken(['orders', 'products']);

Solution

  1. Step 1: Review createToken method signature

    The createToken method accepts the token name as first argument and an array of scopes as second argument.
  2. Step 2: Evaluate each option

    $token = $user->createToken('api-token', ['orders', 'products']); correctly passes the token name and scopes array. $token = $user->createToken('api-token')->scopes(['orders', 'products']); incorrectly chains scopes() which does not exist. $token = $user->createToken('api-token', 'orders', 'products'); passes scopes as separate arguments, which is invalid. $token = $user->createToken(['orders', 'products']); passes scopes as first argument without token name.
  3. Final Answer:

    $token = $user->createToken('api-token', ['orders', 'products']); -> Option C
  4. Quick Check:

    createToken(name, scopes array) = correct [OK]
Hint: Pass scopes as second argument array in createToken() [OK]
Common Mistakes:
  • Passing scopes as separate arguments instead of array
  • Trying to chain scopes() method
  • Omitting token name argument