Laravel Sanctum is a simple and lightweight authentication system designed specifically for API authentication in Laravel applications. It provides a straightforward way to authenticate users via tokens while being easy to implement and manage. Sanctum is ideal for SPAs (Single Page Applications) or simple mobile applications, where you want to authenticate users using a traditional session or API tokens.
Key Features of Laravel Sanctum:
- API Token Authentication: Allows users to generate API tokens that can be used to authenticate against your application.
- SPA Authentication: Supports traditional session-based authentication for SPAs using cookies.
- Token Scopes: You can define scopes to limit access for different tokens, providing granular control over what users can do with their tokens.
- Lightweight: Unlike OAuth2 solutions like Passport, Sanctum is much simpler and designed for basic authentication needs.
- Multiple Token Types: Supports both personal access tokens and simple token authentication for API requests.
Installation
To install and set up Laravel Sanctum, follow these steps:
- Install Laravel Sanctum: Use Composer to install Sanctum:
1composer require laravel/sanctum - Run Migrations: Publish the Sanctum migration files and migrate them to create the necessary database tables:
12php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"php artisan migrate - Add Sanctum Middleware: Add the
Sanctum
middleware to yourapi
middleware group in theapp/Http/Kernel.php
file:
1234567protected $middlewareGroups = ['api' => [\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,'throttle:api',\Illuminate\Routing\Middleware\SubstituteBindings::class,],]; - Use HasApiTokens Trait: In your
User
model (app/Models/User.php
), include theHasApiTokens
trait:
123456use Laravel\Sanctum\HasApiTokens;class User extends Authenticatable{use HasApiTokens, Notifiable;} - Configure Authentication Guards: In your
config/auth.php
, you should set theapi
guard to usesanctum
:
1234567891011'guards' => ['web' => ['driver' => 'session','provider' => 'users',],'api' => ['driver' => 'sanctum','provider' => 'users',],],
Authentication Process with Sanctum
1. API Token Authentication:
Users can generate tokens for accessing APIs. Here’s how to create and use tokens:
- Creating Tokens: Users can create personal access tokens like this:
1$token = $user->createToken('Token Name')->plainTextToken; - Using Tokens: Use the generated token to authenticate API requests. Simply include it in the
Authorization
header:
1 |
Authorization: Bearer YOUR_TOKEN_HERE |
- Example API Request: Here’s how to set up a route and controller method to protect with Sanctum:
1 2 3 |
Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); |
2. Session-Based Authentication:
Sanctum also allows session-based authentication for SPAs. Here’s how to set it up:
- Login: When a user logs in, you can create a session:
123456789Route::post('/login', function (Request $request) {$credentials = $request->only('email', 'password');if (Auth::attempt($credentials)) {return response()->json(['message' => 'Logged in successfully'], 200);}return response()->json(['message' => 'Invalid credentials'], 401);}); - Logout: Users can log out by invalidating the session:
1234Route::post('/logout', function (Request $request) {Auth::logout();return response()->json(['message' => 'Logged out successfully'], 200);});
Token Scopes
You can define scopes to provide different permissions for different tokens. Here’s how to implement scopes in Sanctum:
- Defining Scopes: When creating a token, you can define scopes:
1$token = $user->createToken('Token Name', ['place-orders'])->plainTextToken; - Protecting Routes: You can protect your routes based on scopes:
123Route::middleware('auth:sanctum', 'scope:place-orders')->post('/orders', function (Request $request) {// Logic to place order});
Summary of Use Cases:
- Single Page Applications (SPAs): Use Sanctum for session-based authentication to maintain a seamless user experience.
- Mobile Applications: Use personal access tokens for API authentication when users access the API via mobile apps.
- API Development: Ideal for simple APIs where you don’t need the complexity of OAuth2.
Conclusion
Laravel Sanctum is a powerful and flexible authentication system that strikes a balance between simplicity and functionality, making it an excellent choice for developers looking to secure their APIs without the overhead of a full OAuth2 server like Passport.