How to install and Use Laravel Sanctum for Authentication
Posted on August 26th, 2024
Laravel Sanctum offers a straightforward and efficient solution for incorporating authentication into your Laravel applications. If you’re developing a Single-Page Application (SPA), a mobile app, or need a basic API token setup, Sanctum is an excellent tool to consider. Its simplicity and ease of use make it a compelling choice for developers looking for a hassle-free authentication system.
Sanctum stands out as a user-friendly alternative to Laravel Passport, especially when you don’t require the intricate features of OAuth2. Its setup process is more streamlined, allowing you to get up and running with authentication quickly. Whether you’re managing user sessions or handling API tokens, Sanctum provides a seamless way to integrate these features without the complexity of more advanced systems.
In essence, Laravel Sanctum is ideal for projects that need reliable and straightforward authentication without the overhead of more advanced solutions. Its design ensures that you can implement authentication efficiently, focusing on building and enhancing your application rather than dealing with intricate configuration and management.
Why Use Laravel Sanctum?
With Laravel Sanctum, you can:
- Create and use API tokens: Easily secure your API with tokens, providing a simple method for authenticating requests. This is especially useful for applications where you need to allow third-party integrations or provide access to specific parts of your system.
- Protect routes in SPAs: Ensure that only authenticated users can access certain parts of your Single-Page Application (SPA). Sanctum makes it simple to restrict access to specific routes, enhancing the security and user experience of your application.
- Session-based authentication: Manage user sessions with minimal setup, which is ideal for web applications where users need to stay logged in as they navigate between pages. Sanctum handles session management efficiently, allowing you to focus on building your application’s features.
- Support for mobile apps: Sanctum’s token-based authentication is well-suited for mobile applications, making it easier to handle secure interactions between your app and backend services.
- Easy integration with Laravel: Since Sanctum is designed specifically for Laravel, it integrates seamlessly with the framework, making it easier to implement and maintain compared to external authentication systems.
- Flexible and lightweight: Unlike more complex systems like OAuth2, Sanctum provides a lightweight and flexible approach to authentication, making it a perfect fit for projects that don’t require the full range of OAuth2 features.
Sanctum is ideal if you need a simple, secure way to handle authentication without dealing with the complexities of other systems. Its ease of use and integration with Laravel ensure that you can implement robust authentication with minimal hassle.
What You Need Before Starting
Before you dive in, make sure you have:
- A Laravel project up and running.
- Basic knowledge of how Laravel’s authentication works.
- Familiarity with PHP.
Step-by-Step Guide to Setting Up Laravel Sanctum
Step 1: Start a New Laravel Project (if you don’t have one yet) by creating one easily with Composer if you still need to get a Laravel project.
You can create one easily with Composer if you still need to get a Laravel project. Open your terminal and run:
composer create-project --prefer-dist laravel/laravel my-laravel-app
Then, navigate into your project folder:
cd my-laravel-app
Step 2: Install Sanctum by running the command to add it to your project.
Next, you need to install Sanctum. Run this command in your terminal:
composer require laravel/sanctum
Step 3: Publish the Sanctum Configuration to create necessary configuration files in your project.
Sanctum needs some configuration files, so publish them using this Artisan command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This will create a sanctum.php file in the config directory of your Laravel project.
Step 4: Create the Necessary Database Tables by running the migration command.
Sanctum uses a database table to store the API tokens. To create this table, run:
php artisan migrate
Step 5: Update Middleware to protect your API routes by adding the Sanctum middleware.
You’ll need to update the api middleware to protect your API routes. Open the app/Http/Kernel.php file and add the Sanctum middleware like this:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Step 6: Configure for SPAs (If Needed) to ensure proper handling of CORS.
If you’re using Sanctum with an SPA, ensure your SPA and Laravel app are correctly set up to handle CORS and are on the same domain.
Step 7: Create API Tokens by using code in your controller to generate a token for a user.
To create an API token for a user, you can use this simple code in your controller:
$user = User::find(1);
$token = $user->createToken('MyAppToken')->plainTextToken;
This will generate a new token that the user can use to authenticate API requests.
Step 8: Protect Your API Routes by adding the auth:sanctum middleware to your routes.
To make sure only authenticated users can access specific routes, add the auth:sanctum middleware to your routes in routes/api.php:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Step 9: Revoke Tokens by using the appropriate method to delete a user’s token.
If a user no longer needs a token, you can delete it like this:
$user->tokens()->delete();
Step 10: Test Your Authentication by using a tool like Postman for validating your API routes.
It’s essential to test that everything is working. You can use a tool like Postman to test your API routes. After you’ve issued a token, include it in your API requests like this:
Authorization: Bearer {token}
Step 11: Keep Your Routes Secure by protecting sensitive routes with the auth:sanctum middleware.
Always protect sensitive routes with the auth:sanctum middleware to ensure only authenticated users can access them.
Step 12: Handle Errors Gracefully by checking token validity before allowing access.
Make sure your app handles errors well. For example, check if the token is valid before allowing access:
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
Step 13: Laravel Sanctum is versatile and can be used for various real-world use cases like API Authentication.
Laravel Sanctum is versatile and can be used for:
- API Authentication: Secure your API with token-based authentication.
- SPAs and Mobile Apps: Manage user authentication easily for SPAs and mobile apps.
- Microservices: Secure communication between microservices using tokens.
Conclusion
Laravel Sanctum is a simple yet powerful tool for adding authentication to your Laravel projects. Whether you’re building an API, SPA, or mobile app, Sanctum makes it easy to secure your application. By following these steps, you can quickly get started with Sanctum and enhance the security of your Laravel projects.