Learn to secure your Laravel API using Sanctum. We'll cover installation, route configuration, and token generation to authenticate your users effectively.
Previously in this course, we explored service-oriented task management to keep our business logic clean and decoupled. Now that our core application logic is structured, it is time to expose that functionality via a secure interface. In this lesson, we will implement token-based authentication using Laravel Sanctum, transforming our application into a robust API.
When building a stateless API, traditional session-based authentication (which relies on cookies) is often insufficient, especially for mobile apps or third-party integrations. Laravel Sanctum provides a lightweight authentication system that allows you to issue API tokens to users.
Sanctum works by attaching a token to the Authorization header of an incoming request. When the server receives a request, the auth:sanctum middleware intercepts it, verifies the token against the personal_access_tokens table, and identifies the authenticated user.
First, install Sanctum via Composer:
Bashcomposer require laravel/sanctum
Next, publish the configuration file and run the migrations to create the necessary database tables:
Bashphp artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate
Finally, ensure the HasApiTokens trait is added to your User model. This trait provides the methods necessary to issue tokens and verify abilities:
PHPnamespace App\Models; use Laravel\Sanctum\HasApiTokens; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; }
To allow users to authenticate, we need an endpoint that accepts credentials and returns a plain-text token. In a production environment, you would typically handle this in an AuthController.
Here is a concrete example of how to generate a token:
PHPpublic function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', 'device_name' => 'required', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } #6A9955">// Generate the token $token = $user->createToken($request->device_name)->plainTextToken; return response()->json(['token' => $token], 200); }
The createToken method returns a NewAccessToken instance. The plainTextToken property is the only time you will see the full token; ensure you return this to the client, as you cannot retrieve it again later.
With the authentication logic in place, we need to protect our routes. Open routes/api.php. Sanctum automatically registers the auth:sanctum middleware, which you can apply to your routes to ensure only authenticated users can access them.
PHPuse Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->group(function () { Route::get('/user', function (Request $request) { return $request->user(); }); Route::apiResource('tasks', TaskController::class); });
By grouping these routes, any request missing a valid Authorization: Bearer {token} header will receive a 401 Unauthorized response.
LoginController if you haven't already.login method shown above.curl to send a POST request to your login endpoint./api/user endpoint by adding the header: Authorization: Bearer YOUR_TOKEN_HERE.HasApiTokens to your User model, the createToken method will not exist, leading to a "method not found" error.$token object from your controller. It contains metadata that should not be exposed. Always return the plainTextToken string.Authorization: Bearer {token}. A common mistake is omitting the Bearer prefix.php artisan migrate. Without the personal_access_tokens table, authentication will fail silently or throw a query exception.We have successfully integrated Sanctum into our project. We installed the package, prepared our User model, implemented a token generation flow, and secured our API routes using middleware. This foundation allows us to move forward with building sophisticated API resources that are both secure and easy to maintain.
Up next: We will explore Resource Controllers and API Responses to ensure our data is transformed consistently before it reaches the client.
Stop manually testing your forms. Learn how to use Laravel's testing suite to automate validation checks, simulate authenticated users, and ensure data integrity.
Read moreLearn how to use Laravel API resources to transform model data and return consistent, clean JSON responses for your RESTful applications.
REST API Fundamentals with Sanctum
Implementing Middleware for API Security
Database Transactions for Data Integrity
Error Handling and Global Exceptions
Introduction to Laravel Events and Listeners
Asynchronous Processing with Queues
Job Chaining and Batching
Feature Testing Fundamentals
Mocking Services and Repositories in Tests
Testing Events and Jobs
Database Factories and Seeding
API Versioning Strategies
Advanced Request Filtering and Sorting
Handling File Uploads in REST APIs
Real-time Notifications with Broadcasting
Using Observers for Model Lifecycle Hooks
Implementing Policies for Authorization
Customizing Authentication Guards
Rate Limiting API Endpoints
Eloquent Performance Optimization
Caching Strategies for Performance
Using Traits for Code Reuse
Advanced Dependency Injection with Service Providers
Command Line Tools with Artisan
Scheduled Tasks and Cron Jobs
Integrating Third-Party Services
Handling Webhooks
Logging and Monitoring
Database Migrations Best Practices
Advanced Testing: Integration Tests
Testing API Authentication
Code Quality and Static Analysis
Project Structure for Large Applications
Environment and Configuration Management
Deploying Laravel Applications
Database Indexing Strategies
Using Value Objects
Strategy Pattern for Business Rules
Advanced Queue Monitoring
Building a Search API
Handling Concurrency and Race Conditions
API Documentation with OpenAPI
Testing with Test Doubles
Implementing Multi-Tenancy
Refactoring Legacy Code
Using Middleware for Feature Flags
Building Reusable Packages
Performance Profiling
Secure API Design
Event Sourcing Concepts