Mastering API Authentication with Laravel Sanctum
Overview
Prerequisites
To follow this guide, you should be comfortable with the
Key Libraries & Tools
- Laravel Sanctum: The core package for issuing and validating API tokens.
- HasApiTokens Trait: A crucial trait added to the User model to enable token management methods.
- Personal Access Tokens Table: The migration-generated table where Sanctum stores hashed token data.
Code Walkthrough
First, equip your User model with the necessary capabilities. Adding the trait gives you access to methods like createToken().
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
To generate a token, call createToken and specify a name. It is vital to grab the plainTextToken immediately, as Sanctum only stores a hashed version for security.
$user = User::first();
$token = $user->createToken('my-app-name')->plainTextToken;
When making requests, you must pass this string in the Authorization header as a Bearer token. Laravel's HTTP client makes this easy with the withToken() method:
$response = Http::withToken($token)->get('https://api.test/movies');
Syntax Notes
Sanctum uses Abilities to handle fine-grained permissions. By default, a token might have a ['*'] ability, granting full access. You can restrict tokens by passing an array of specific strings during creation, such as ['movies:read']. This is checked via the ability or abilities middleware in your routes.
Practical Examples
Imagine a mobile app where users only need to view data but not update it. You would issue a token with a read-only ability. If that token is hijacked, the attacker cannot perform destructive actions like deleting records because the Sanctum middleware will block any request lacking the required scope.
Tips & Gotchas
- The Plain Text Trap: You can only access the unhashed token once at the moment of creation. If you don't show it to the user then, it's gone forever.
- Middleware Order: Always ensure the
auth:sanctummiddleware is applied before any ability checks in your route files to ensure the user is identified first.
