0
0
Laravelframework~15 mins

API authentication with Sanctum in Laravel - Deep Dive

Choose your learning style9 modes available
Overview - API authentication with Sanctum
What is it?
API authentication with Sanctum is a way to securely identify users making requests to a Laravel application's API. It allows users to log in and receive a token that proves who they are when calling protected routes. Sanctum manages these tokens simply and safely without complex setups. This helps apps know which user is making each request.
Why it matters
Without API authentication, anyone could access private data or perform actions they shouldn't. Sanctum solves this by giving each user a unique token to prove their identity. This protects user data and app functionality from unauthorized access. Without it, apps would be insecure and users' information could be exposed or misused.
Where it fits
Before learning Sanctum, you should understand basic Laravel routing, controllers, and middleware. Knowing how HTTP requests and responses work helps too. After mastering Sanctum, you can explore more advanced API security like OAuth or Passport, and learn about token scopes and permissions.
Mental Model
Core Idea
Sanctum gives each user a secret token that acts like a digital ID card to prove who they are when using an API.
Think of it like...
Imagine a concert where attendees get wristbands at the entrance. The wristband shows they paid and can enter certain areas. Sanctum tokens are like those wristbands for API users.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   User logs   │──────▶│ Sanctum issues │──────▶│ User gets token│
│    in via     │       │   token for    │       │  (digital ID) │
│   API client  │       │ authentication │       └───────────────┘
└───────────────┘       └───────────────┘               │
                                                        ▼
                                               ┌─────────────────┐
                                               │ API receives     │
                                               │ token with each  │
                                               │ request to check │
                                               │ user identity    │
                                               └─────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding API Authentication Basics
🤔
Concept: Learn what API authentication means and why tokens are used.
API authentication is how an app knows who is making a request. Instead of usernames and passwords sent every time, apps use tokens. Tokens are like secret keys given after login. They prove identity without sharing passwords repeatedly.
Result
You understand why tokens are safer and how they help APIs know who is calling them.
Knowing the purpose of tokens helps you see why Sanctum uses them instead of passwords for every API call.
2
FoundationInstalling and Setting Up Sanctum
🤔
Concept: Learn how to add Sanctum to a Laravel project and configure it.
Run 'composer require laravel/sanctum' to add Sanctum. Then publish its config and migration files with 'php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"'. Run migrations to create the needed tables. Finally, add Sanctum's middleware to your API routes in 'api.php'.
Result
Sanctum is ready to issue and manage tokens in your Laravel app.
Setting up Sanctum correctly is crucial because it creates the database tables and middleware that handle token authentication.
3
IntermediateIssuing Tokens on User Login
🤔Before reading on: do you think Sanctum automatically creates tokens on login, or do you need to write code to generate them? Commit to your answer.
Concept: Learn how to generate tokens for users after they log in.
After validating user credentials, call '$user->createToken('token-name')->plainTextToken' to create a token. Return this token to the client. The client stores it and sends it with future API requests in the Authorization header as 'Bearer {token}'.
Result
Users receive a token they can use to authenticate API requests.
Understanding that token creation is manual lets you control when and how tokens are issued, improving security and flexibility.
4
IntermediateProtecting Routes with Sanctum Middleware
🤔Before reading on: do you think Sanctum protects routes by checking tokens automatically, or do you need to add middleware to routes? Commit to your answer.
Concept: Learn how to restrict API routes so only authenticated users with valid tokens can access them.
Add 'auth:sanctum' middleware to routes or route groups in 'routes/api.php'. This tells Laravel to check the token sent with requests. If the token is missing or invalid, Laravel returns a 401 Unauthorized response.
Result
Only requests with valid Sanctum tokens can access protected API routes.
Knowing that middleware enforces token checks helps you secure specific parts of your API without affecting public routes.
5
IntermediateUsing Token Abilities to Limit Access
🤔Before reading on: do you think all tokens have the same permissions by default, or can you assign specific abilities? Commit to your answer.
Concept: Learn how to assign abilities (scopes) to tokens to control what actions users can perform.
When creating a token, pass an array of abilities like '$user->createToken('token-name', ['create', 'update'])->plainTextToken'. In routes or controllers, check abilities with '$request->user()->tokenCan('create')'. This limits what the token can do.
Result
Tokens can have fine-grained permissions, improving security by limiting access.
Understanding token abilities lets you build APIs where users have different levels of access based on their token.
6
AdvancedManaging Token Revocation and Expiry
🤔Before reading on: do you think Sanctum tokens expire automatically, or do you need to handle revocation manually? Commit to your answer.
Concept: Learn how to revoke tokens and manage their lifespan.
Sanctum tokens do not expire by default. You can revoke tokens by deleting them from the database using '$user->tokens()->delete()' or '$user->tokens()->where('id', $tokenId)->delete()'. To add expiry, implement custom logic or use Laravel's built-in features like Passport for more complex needs.
Result
You can control when tokens stop working, improving security by invalidating old or compromised tokens.
Knowing that Sanctum tokens persist until revoked helps prevent security risks from forgotten tokens.
7
ExpertSanctum's SPA Authentication Mode Explained
🤔Before reading on: do you think Sanctum uses tokens for SPA authentication, or does it use cookies and sessions? Commit to your answer.
Concept: Learn how Sanctum handles authentication differently for single-page applications (SPAs) using cookies instead of tokens.
For SPAs on the same domain, Sanctum uses Laravel's session cookies to authenticate users instead of API tokens. This avoids storing tokens in JavaScript and leverages built-in CSRF protection. The SPA sends requests with cookies, and Sanctum's middleware validates the session. This mode requires configuring CORS and CSRF properly.
Result
SPAs can authenticate securely without managing tokens manually, improving developer experience and security.
Understanding Sanctum's dual modes clarifies when to use token-based API authentication versus cookie-based SPA authentication.
Under the Hood
Sanctum stores API tokens in a database table linked to users. When a request comes in with a token, Sanctum checks the token's validity by matching it to a user record. It uses Laravel's middleware to intercept requests and perform this check before the app processes the request. For SPA mode, Sanctum relies on Laravel's session cookies and CSRF tokens to authenticate users without tokens.
Why designed this way?
Sanctum was designed to be simple and lightweight compared to OAuth solutions. It focuses on token-based API authentication and SPA cookie authentication without complex protocols. This design choice makes it easy for developers to add secure API authentication without overhead. Alternatives like Passport are more complex and suited for large-scale OAuth needs.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ API Request   │──────▶│ Sanctum       │──────▶│ Token checked │
│ with token   │       │ Middleware    │       │ in database   │
└───────────────┘       └───────────────┘       └───────────────┘
        │                      │                        │
        ▼                      ▼                        ▼
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Valid token?  │──────▶│ User identified│──────▶│ Request passed │
│ (yes/no)      │       │ or rejected   │       │ to app logic   │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do Sanctum tokens expire automatically after some time? Commit to yes or no.
Common Belief:Sanctum tokens expire automatically after a set time like session cookies.
Tap to reveal reality
Reality:Sanctum tokens do not expire by default and remain valid until manually revoked or deleted.
Why it matters:Assuming tokens expire can lead to security risks if old tokens remain active and are compromised.
Quick: Does Sanctum require OAuth to work? Commit to yes or no.
Common Belief:Sanctum is just a simpler version of OAuth and requires OAuth setup.
Tap to reveal reality
Reality:Sanctum is independent and does not require OAuth. It uses simple token or cookie-based authentication.
Why it matters:Confusing Sanctum with OAuth can cause unnecessary complexity and setup delays.
Quick: Can Sanctum tokens be used for SPA authentication by default? Commit to yes or no.
Common Belief:Sanctum tokens are always used for SPA authentication.
Tap to reveal reality
Reality:Sanctum uses cookie-based session authentication for SPAs, not tokens, to improve security and ease.
Why it matters:Using tokens for SPAs unnecessarily exposes tokens in JavaScript and complicates CSRF protection.
Quick: Does adding 'auth:sanctum' middleware automatically protect all routes? Commit to yes or no.
Common Belief:Adding 'auth:sanctum' middleware protects all routes globally without specifying.
Tap to reveal reality
Reality:You must explicitly add 'auth:sanctum' middleware to routes or groups to protect them.
Why it matters:Forgetting to add middleware leaves routes unprotected, exposing sensitive data.
Expert Zone
1
Sanctum tokens are hashed in the database for security, so the plain token is only visible once at creation.
2
Sanctum supports multiple tokens per user, allowing different devices or clients to have separate tokens with distinct abilities.
3
Sanctum's SPA mode requires careful CORS and CSRF configuration to avoid security holes, which is often overlooked.
When NOT to use
Sanctum is not ideal for complex OAuth scenarios requiring third-party authorization or social login. In such cases, Laravel Passport or external OAuth providers are better choices.
Production Patterns
In production, developers often combine Sanctum token abilities with custom middleware to enforce fine-grained API permissions. Tokens are stored securely on clients, and token revocation endpoints are implemented to allow users to log out from devices.
Connections
OAuth 2.0
Sanctum is a simpler alternative to OAuth 2.0 for API authentication.
Understanding OAuth helps appreciate Sanctum's simplicity and when to choose one over the other.
HTTP Cookies and Sessions
Sanctum uses cookies and sessions for SPA authentication mode.
Knowing how cookies and sessions work clarifies how Sanctum secures SPAs without tokens.
Physical Access Control Systems
Both use tokens or badges to grant access to protected resources.
Seeing API tokens like access badges helps understand authentication as a gatekeeper process.
Common Pitfalls
#1Leaving API routes unprotected by forgetting middleware.
Wrong approach:Route::get('/user', function () { return auth()->user(); });
Correct approach:Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); });
Root cause:Not adding 'auth:sanctum' middleware means Laravel does not check tokens, leaving routes open.
#2Exposing plain tokens in logs or responses after creation.
Wrong approach:return response()->json(['token' => $user->createToken('app')->plainTextToken]); // logs or stores token insecurely
Correct approach:Return token only once securely to client and never store or log it in plain text.
Root cause:Misunderstanding that tokens are secret and should be treated like passwords.
#3Using tokens for SPA authentication instead of cookies.
Wrong approach:SPA stores token in localStorage and sends it manually with each request.
Correct approach:Use Sanctum's SPA mode with cookie-based session authentication and proper CSRF tokens.
Root cause:Not knowing Sanctum's SPA mode leads to insecure token handling and CSRF vulnerabilities.
Key Takeaways
Sanctum provides simple, secure API authentication using tokens or cookies depending on the client type.
Tokens act like secret ID cards that prove user identity for API requests without sending passwords repeatedly.
Protecting routes with 'auth:sanctum' middleware ensures only authenticated users can access sensitive endpoints.
Sanctum tokens do not expire automatically; you must revoke them manually to maintain security.
Sanctum's SPA mode uses cookie-based authentication to improve security and developer experience for single-page apps.