Laravel Sanctum: A Comprehensive Guide to Token-Based Authentication
What is Laravel Sanctum?
Laravel Sanctum is a lightweight package for token-based authentication in Laravel applications. It provides a simple and secure way to authenticate your APIs using API tokens, personal access tokens, or temporary tokens that expire after a certain period of time.
One of the primary advantages of using Laravel Sanctum is that it’s very easy to use. You don’t have to set up complex authentication systems like OAuth or JWT. Instead, you can create a token-based authentication system with just a few lines of code.
Set Up a Headless CMS in Laravel Using Strapi: complete tutorial with benefit
Setting up Laravel Sanctum
Before you can start using Laravel Sanctum, you need to install it into your Laravel application. You can do this using Composer by running the following command:
composer require laravel/sanctum
Once you have installed Laravel Sanctum, you need to publish its configuration file. You can do this by running the following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This command will publish Sanctum’s configuration file to your application’s config directory.
Configuring Laravel Sanctum
After publishing the configuration file, you need to configure Laravel Sanctum. You can do this by opening the newly created config/sanctum.php file and configuring the options to suit your needs.
Some of the options you might want to configure include:
- The stateful domain: This is the domain that Sanctum will use to determine whether a user is authenticated or not. By default, it’s set to your application’s root domain, but you can change it to suit your needs.
- The guard: This is the authentication guard that Sanctum will use to authenticate requests. By default, it’s set to the ‘web’ guard, but you can change it to any other guard that you have set up in your application.
- The expiration: This is the amount of time that tokens will remain valid before they expire. By default, it’s set to 1 hour, but you can change it to suit your needs.
Creating Tokens with Laravel Sanctum
Once you have configured Laravel Sanctum, you can start creating tokens. There are three types of tokens you can create with Sanctum:
- API Tokens: These are tokens that are used to authenticate API requests.
- Personal Access Tokens: These are tokens that are used to authenticate users for a longer period of time. You can use them to create “remember me” functionality or to allow users to stay logged in across multiple devices.
- Temporary Tokens: These are tokens that expire after a certain period of time. You can use them to authenticate users for a specific period of time, such as when they are completing a task.
Creating an API Token with Laravel Sanctum
To create an API token with Laravel Sanctum, you need to call the createToken method on an authenticated user. For example:
<?php
use Illuminate\Http\Request;
Route::middleware('auth')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
$user = $request->user();
$token = $user->createToken('API Token')->plainTextToken;
return ['token' => $token];
});
In this example, we are creating an API route that allows users to create an API token. The route is protected by the ‘auth’ middleware, which means that only authenticated users can access it.
When a user sends a POST request to the ‘/tokens/create’ endpoint, the server creates a new API token for the user and returns it in the response. The ‘createToken’ method creates a new token for the authenticated user and returns a ‘PersonalAccessTokenResult’ object. We then retrieve the plain text token from this object and return it in the response.
Creating a Personal Access Token with Laravel Sanctum
To create a personal access token with Laravel Sanctum, you need to use the ‘create’ method on the ‘PersonalAccessToken’ model. For example:
<?php
use Illuminate\Http\Request;
use Laravel\Sanctum\PersonalAccessToken;
Route::middleware('auth')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
$user = $request->user();
$token = $user->createToken('API Token')->plainTextToken;
return ['token' => $token];
});
Route::post('/personal-access-tokens/create', function (Request $request) {
$user = $request->user();
$token = $user->createToken('Personal Access Token', ['*']);
return ['token' => $token->plainTextToken];
});
In this example, we have added a new route that allows users to create a personal access token. The ‘create’ method on the ‘PersonalAccessToken’ model creates a new personal access token for the authenticated user. We pass the name of the token as the first argument and an array of abilities as the second argument. The ‘*’ symbol means that the token has all abilities.
After creating the token, we return its plain text value in the response.
Using Tokens with Laravel Sanctum
Once you have created a token, you can use it to authenticate API requests. To do this, you need to include the token in the request headers.
For example:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
In this example, we have created a new API route that returns the authenticated user. The route is protected by the ‘auth:sanctum’ middleware, which means that it requires an API token to access.
To authenticate the request, the client needs to include the token in the ‘Authorization’ header of the request. The header should look like this:
Authorization: Bearer {API_TOKEN}
Where {API_TOKEN} is the value of the API token that was created earlier.
Conclusion
Laravel Sanctum is a powerful package for securing APIs in Laravel applications. With its easy-to-use token-based authentication system, you can quickly add authentication to your APIs without having to go through the complexity of setting up OAuth or JWT.
In this guide, we have explored everything you need to know about Laravel Sanctum, from installation and configuration to creating and using tokens. By following the examples provided, you should be able to add secure token-based authentication to your Laravel application’s APIs.
Remember, security is always a top priority when it comes to web applications, so make sure to keep your Laravel application up-to-date with the latest security patches and best practices.
Recent Comments