Laravel API Authentication with Sanctum
Securing your Laravel APIs is crucial. This tutorial provides a step-by-step guide to implementing robust authentication using Laravel Sanctum, covering everything from installation to advanced customization. Learn how to protect your API endpoints and build secure, scalable applications.
What is Laravel Sanctum and Why Use It?
Laravel Sanctum is a lightweight authentication package specifically designed for Single-Page Applications (SPAs), mobile applications, and simple, token-based APIs. It provides a simple and secure way to authenticate users accessing your API without the complexities of traditional OAuth flows. It uses API tokens that are scoped, meaning you can grant different permissions to different tokens.
Key benefits of using Laravel Sanctum:
- Simple to set up: Sanctum is easy to install and configure, requiring minimal code changes.
- Lightweight: It's a lightweight package that doesn't add unnecessary overhead to your application.
- Secure: Sanctum uses secure API tokens to authenticate users.
- Scoped tokens: Define abilities (permissions) for each token.
- SPA Authentication: Seamlessly integrates with Single-Page Applications.
Prerequisites
Before you begin, ensure you have the following:
- A Laravel project (version 8 or higher).
- PHP 7.3 or higher.
- Composer installed.
- A database connection configured.
Step-by-Step Guide to Implementing Laravel Sanctum Authentication
Step 1: Install Laravel Sanctum
Install the Sanctum package using Composer:
composer require laravel/sanctum
Step 2: Publish Configuration and Migration Files
Publish the Sanctum configuration and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This command will publish the config/sanctum.php
configuration file and a migration file to your database migrations directory.
Step 3: Run Database Migrations
Run the database migrations to create the necessary tables:
php artisan migrate
This will create the personal_access_tokens
table, which Sanctum uses to store API tokens.
Step 4: Configure the User Model
Ensure your App\Models\User
model uses the HasApiTokens
trait:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
// ... other model configurations
}
Step 5: Create API Routes
Define your API routes in the routes/api.php
file. Protect these routes using the auth:sanctum
middleware.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
Route::post('/logout', [AuthController::class, 'logout']);
});
Step 6: Create Authentication Controller
Create an AuthController
to handle user registration, login, and logout. Here’s an example:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid login credentials'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json([
'message' => 'Successfully logged out'
]);
}
}
Step 7: Test Your API
Use tools like Postman or Insomnia to test your API endpoints. Register a new user, log in, and then access the protected /api/user
endpoint using the obtained token.
Advanced Customization
Token Abilities (Scopes)
Sanctum allows you to define abilities (scopes) for each token. This is useful for granting different permissions to different tokens. For example, you can create a token with read-only access or a token with full access.
To define abilities, modify the createToken
method:
$token = $user->createToken('auth_token', ['server:update'])->plainTextToken;
Then, in your routes, you can check for these abilities:
Route::middleware(['auth:sanctum', 'ability:server:update'])->group(function () {
// Routes that require the 'server:update' ability
});
Consider exploring other authentication methods, like using Passport for more complex OAuth2 implementations if your application requires it. You can also integrate AI-powered security tools to enhance your application's security. Read more about Supercharge Your Website with AI: Codimate Solutions' Innovative Approach.
FAQ: Laravel Sanctum Authentication
What is the difference between Laravel Sanctum and Passport?
Laravel Sanctum is designed for simple API authentication, SPAs, and mobile apps, using lightweight tokens. Laravel Passport, on the other hand, is a full-fledged OAuth2 server implementation, suitable for more complex scenarios requiring third-party access and authorization. Sanctum is easier to set up for basic API security, while Passport provides a more robust and standardized approach for larger applications needing OAuth2 features.
How do I handle token expiration in Laravel Sanctum?
Laravel Sanctum doesn't provide built-in token expiration. However, you can implement token expiration by adding a column to the personal_access_tokens
table (e.g., expires_at
) and setting a middleware to check the token's expiration date. If the token has expired, you can revoke it. Another approach is to use refresh tokens, which are commonly used in OAuth2 flows but can be adapted for Sanctum as well.
How can I protect my API routes from CSRF attacks when using Sanctum with SPAs?
When using Sanctum with SPAs, CSRF protection is handled through Sanctum's built-in CSRF protection. Sanctum automatically sets a CSRF token in a cookie (XSRF-TOKEN
) and expects the SPA to send this token in the X-XSRF-TOKEN
header with each request. Laravel's VerifyCsrfToken
middleware then validates this token, preventing CSRF attacks. Make sure your SPA is configured to read the CSRF token from the cookie and include it in the header.
How do I revoke or delete a Sanctum token?
You can revoke a Sanctum token by deleting it from the personal_access_tokens
table. Here’s how you can do it in your controller:
use Illuminate\Http\Request;
public function revokeToken(Request $request, $tokenId)
{
$token = $request->user()->tokens()->find($tokenId);
if ($token) {
$token->delete();
return response()->json(['message' => 'Token revoked']);
} else {
return response()->json(['message' => 'Token not found'], 404);
}
}
This allows a user to revoke their own tokens. For admin revocation, you can adjust the query to find tokens based on user ID and token ID.
Conclusion
Laravel Sanctum provides a simple and secure way to authenticate your APIs. By following this tutorial, you can easily implement authentication in your Laravel applications. Remember to explore advanced customization options like token abilities to further enhance your API's security. Consider optimizing your application for peak performance using techniques discussed in Unlocking Peak Performance: Advanced Web Application Optimization Strategies.