How to Use Laravel Sanctum for API Authentication
Laravel Sanctum is a popular package that provides a simple and effective way to manage API authentication in Laravel applications. Whether you’re building single-page applications (SPAs), mobile apps, or simple APIs, Sanctum makes it easy to authenticate users through token-based systems. In this article, we will delve into how to use Laravel Sanctum for API authentication effectively.
What is Laravel Sanctum?
Laravel Sanctum is a light-weight authentication system for APIs built on top of Laravel. It allows developers to issue API tokens to users for authentication and provides a straightforward way to manage user sessions for SPAs. Unlike Laravel Passport, which is more robust but complex, Sanctum is designed to be simple to implement and configure.
Installation of Laravel Sanctum
To get started with Laravel Sanctum, you need to install it through Composer. First, run the following command in your terminal:
composer require laravel/sanctum
Once installed, you need to publish the Sanctum configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This command will create a Sanctum configuration file which is located in the config directory. Next, you should run the migrations to create the necessary database tables:
php artisan migrate
Setting Up Sanctum Middleware
To enable Sanctum, you’ll need to add the Sanctum middleware to the API middleware group within your application's HTTP kernel. Open the app/Http/Kernel.php
file and add the following line to the api
middleware group:
'auth:sanctum',
Your modified API middleware group should look something like this:
'api' => [
\Laravel\Sanctum\Http\Middleware\Authenticate::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Configuring User Model
The next step is to ensure that your User model uses the HasApiTokens
trait. This trait allows users to generate tokens for API authentication. Open your User model located at app/Models/User.php
and add the following line:
use Laravel\Sanctum\HasApiTokens;
Also, ensure your User model looks similar to this:
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
Creating API Tokens
To create a token for a user, you can use the following method in your controller or service class:
$user = User::find(1); // Find user by ID
$token = $user->createToken('token-name')->plainTextToken;
This code snippet will generate a new token, which can be returned to the user in their response.
Protecting Routes with Sanctum
You can protect API routes by applying the auth:sanctum
middleware. In your routes file (typically routes/api.php
), you can define routes like this:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Authenticating Users with API Tokens
To authenticate users using the token, the client must send the token in the Authorization header. The format should be as follows:
Authorization: Bearer {token}
After making a request with this header included, Laravel will validate the token, allowing access to the protected routes.
Logging Out Users
If you want to allow users to log out and revoke their API tokens, Sanctum provides an easy way to do that by deleting tokens. You can achieve this by calling the tokens()
method on the authenticated user:
$user->tokens()->delete();
Conclusion
Laravel Sanctum simplifies API authentication by providing a straightforward method for token management and user authentication. By following the steps outlined in this article, you can easily implement API authentication in your