How to Switch from Session-Based Authentication to Token-Based Authentication in Laravel 11 with Sanctum?
To switch from session-based authentication to token-based authentication in Laravel 11 using Sanctum, follow the steps below:
- Install Sanctum: If you haven't installed Sanctum yet, you can install it via composer by running the following command in your terminal:
composer require laravel/sanctum
- Register Sanctum:
After installing Sanctum, you need to register it in your
app/Providers/AppServiceProvider.php
file by adding the following line in theboot()
method:
use Laravel\Sanctum\Sanctum;
if (app()->environment('production')) {
Sanctum::encrypt(config('sanctum.key'));
}
- Update your authentication guard:
You need to update your authentication guard to use token-based authentication. Open your
config/auth.php
file and update theguards
array as follows:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'sanctum',
],
],
- Create an API route:
Create a new route for your API in
routes/api.php
:
Route::middleware('api')->group(function () {
// Your API routes go here
});
- Update your middleware:
Update your middleware to use the
api
guard:
use App\Http\Middleware\AuthenticateApiToken;
Route::middleware([
'auth:api',
])->group(function () {
// Your protected routes go here
});
- Generate a new API key: You can generate a new API key for testing purposes by running the following command in your terminal:
php artisan make:auth api --api
This command will generate a new ApiController
and api.auth
middleware. You can update the ApiController
to return a JSON response instead of the default view response.
- Update your database schema:
You may need to update your database schema to add the
api_token
column to yourusers
table. You can do this by running the following migration:
php artisan migrate
- Test your API:
You can test your API by sending a request to one of your protected routes using a tool like Postman or cURL. Make sure to include the
Authorization
header with aBearer
token:
curl -H "Authorization: Bearer {token}" http://localhost/api/protected
Replace {token}
with a valid API token generated for a user. If everything is set up correctly, you should receive a JSON response with the protected data.