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.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel Advertisement
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling