In this guide, we’ll walk you through the process of using Laravel Sanctum for API token authentication, a lightweight package that simplifies API token and session cookie-based authentication for your Laravel applications. With Sanctum, you can easily secure your APIs without the complexity of OAuth2.
What is Laravel Sanctum?
Laravel Sanctum allows you to manage API tokens for users without the overhead of OAuth. It’s perfect for SPAs (Single Page Applications), mobile applications, and simple token-based APIs.
Prerequisites
Before starting, ensure you have the following:
- Laravel installed in your project.
- A basic understanding of Laravel development.
Installation
First, install Sanctum via Composer:
1
|
composer require laravel/sanctum
|
Next, publish the Sanctum configuration file using Artisan:
1
|
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
|
Finally, run the migrations to create the necessary tables:
1
|
php artisan migrate
|
Setting Up Sanctum
Configuring Middleware
To protect your API and ensure requests have valid tokens, add the Sanctum
middleware to your api
middleware group within your app/Http/Kernel.php
file:
1 2 3 4 5 |
'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], |
Authenticating Users and Issuing Tokens
You can issue tokens to users in your API routes. Here’s a simple example demonstrating how to do so within a controller method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; public function login(Request $request) { $user = User::where('email', $request->email)->first(); if (!$user || !Hash::check($request->password, $user->password)) { return response()->json(['message' => 'Invalid credentials'], 401); } $token = $user->createToken('API Token')->plainTextToken; return response()->json(['token' => $token]); } |
Protecting Routes
To protect your routes, you can use the auth:sanctum
middleware. This ensures that the incoming requests have valid tokens. Add it to any routes you need to secure:
1 2 3 |
Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); |
Related Resources
- Learn how to format URLs with strips in Laravel: Laravel URL Strips
- Learn how to send email with PDF attachment in Laravel: Laravel Email PDF Attachment
- Discover how to update multiple rows in a Laravel controller: Laravel Controller Update Rows
- Set a dynamic sender email in Laravel: Laravel Email Configuration
Conclusion
Laravel Sanctum provides a simple and efficient way to manage API token authentication in your Laravel applications. With minimal configuration and powerful features, Sanctum is a great choice for developers looking to quickly set up secure API authentication.
Implement Sanctum today and enjoy a seamless and safe authentication experience in your Laravel projects!