Labs ICT
โญ Pro Login

API Authentication

Token-based auth with Sanctum.

1 min read | Laravel Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

What Is Sanctum?

Sanctum is Laravel's lightweight authentication package for APIs. It supports both token-based authentication for third-party apps and cookie-based authentication for SPAs.

Installing Sanctum

Install Sanctum through Composer and run the installation command. This publishes the configuration and migration files.


composer require laravel/sanctum

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

Run the migration to create the personal_access_tokens table.


php artisan migrate
    

Personal Access Tokens

Sanctum lets users create named tokens for API access. Each token can have specific abilities or scopes.


use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
}

$user = User::find(1);
$token = $user->createToken('mobile-app', ['read', 'write']);
    

Pass the token in the Authorization header with the Bearer prefix.

SPA Authentication

For single-page applications, Sanctum uses cookie-based authentication. Your SPA makes requests to the same domain, so cookies work naturally.


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

Enable Sanctum's SPA middleware in your kernel and configure your frontend to send credentials with each request.

Protecting Routes

Use the auth:sanctum middleware to protect API routes. Unauthenticated requests receive a 401 response.


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

Sanctum keeps your APIs secure without the complexity of OAuth or JWT.

๐Ÿงช Quick Quiz

What is Laravel Sanctum used for?