Laravel Sanctum API Routes: Protect Endpoints Step by Step

July 30, 2024 · 5 min read

2026 UPDATE - LARAVEL 13
We’re excited to announce that we have updated all of our blog post examples to reflect the new Laravel 13 version! Our previous examples were based on Laravel 10, but with the release of Laravel 13, we wanted to ensure that our readers have access to the most up-to-date information and examples.
What is Laravel Sanctum?
Laravel Sanctum provides a lightweight authentication system for SPAs (single-page applications), mobile applications, and token-based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens can have abilities or scopes that define what actions they can do.
Benefits of Using Laravel Sanctum
Simplicity: Sanctum’s straightforward setup process enables quick and easy implementation of secure API authentication.
Granular Permissions: Define precise actions for tokens, limiting their scope and enhancing security.
CSRF Protection: Sanctum integrates Laravel’s CSRF defense, safeguarding your SPA against common web attacks.
Multiple Tokens: Issue multiple tokens per user, allowing for varied access levels across your application.
Revocable Tokens: Easily revoke tokens to promptly address security breaches or access changes.
Unified Authentication: Manage SPA and API authentication seamlessly within a single system.
User-Friendly Token Management: Allows end-users to effortlessly create and handle their API tokens, promoting self-service security management.
Sanctum Authentication: Cookie Session vs API Tokens
When implementing authentication in web applications, you can choose between cookie based session authentication and token based authentication.
Laravel Sanctum provides support for both methods:
SPA Authentication: Sanctum can be configured to use cookie based session authentication, issuing CSRF tokens and using session cookies, which is ideal for SPAs that are served from the same domain as the backend.
API Token Authentication: Sanctum can also issue API tokens, which can be used for more diverse scenarios, including mobile apps, third-party applications, and SPAs that live on different domains.
Each method has its own use cases, advantages, and drawbacks. We explain Laravel Sanctum Cookie based session Authentication and API Tokens Authentication in detailed posts. Here’s an overview of their differences:
Cookie based Session Authentication
Stateful: This means the server needs to keep track of the user’s session state, typically in a session store or database.
Browser-Specific: Cookies are automatically managed by the web browser and are sent with each request to the same domain that set the cookie. This makes it convenient for traditional web applications.
CSRF Protection: Cookie-based authentication is susceptible to Cross-Site Request Forgery (CSRF) attacks. Therefore, it requires additional security measures like CSRF tokens to protect against such threats.
Same-Origin Policy: Cookies adhere to the same-origin policy, meaning they are only sent to the server if the request is being made to the same domain that set the cookie.
API Token based Authentication
Stateless: The server does not need to keep a record of tokens. The token itself contains all the user information needed for authentication, which is validated every time a request is made.
Cross-Domain/Cross-Origin Requests: Tokens can be sent in HTTP headers or request bodies, allowing for more flexibility with cross-domain or cross-origin requests.
Storage: Tokens are typically stored in local storage or session storage on the client-side and must be manually attached to requests, usually as an Authorization header.
CSRF Immunity: Token-based authentication is not susceptible to CSRF attacks because the token is not automatically sent by the browser. The client application must explicitly attach the token to the request.
Mobile and Single-Page Applications: Token-based authentication is well-suited for mobile apps and SPAs, where the use of cookies might not be as straightforward due to cross-domain issues and the need for API requests to be stateless.
Need a production-ready Laravel API?
Lucky Media builds Laravel backends with React and Next.js frontends for startups. Let's talk
Installing Laravel Sanctum
To get started with Laravel Sanctum, you’ll first need to install the package via the API command:
php artisan install:api
Protecting Routes with Middleware
Sanctum provides middleware that can be applied to your API routes to protect them. This makes sure that only authenticated requests can access those routes.
You can protect your routes by applying the auth:sanctum middleware to your routes in routes/api.php. We have grouped the routes that need to have the Sanctum middleware, so make sure you make these changes on your end.
use App\Http\Controllers\API\UserController;
use App\Http\Controllers\API\PostController;
use App\Http\Controllers\API\AuthController;
Route::middleware(['auth:sanctum'])->group(function () {
// Protected User API routes
Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);
// Protected Post API routes
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
});With this middleware in place, only authenticated requests with a valid Sanctum token can access the protected routes. We created these routes in a previous article named Laravel 13 for Beginners: API Resources.
We explain Laravel Sanctum Cookie based session Authentication for SPAs and API Token Authentication for Mobile Apps in detailed posts.
Conclusion
Laravel Sanctum is a powerful and easy-to-use package that provides a robust system for API token authentication. By using Sanctum, you make sure that your API endpoints are protected and accessible only to authenticated users with valid tokens. Sanctum’s ability to assign specific permissions to tokens also allows you to build a secure and controlled API for your application.
Upcoming Articles in the Series
This article is part of our series Laravel for Beginners: A Step-by-Step Guide to Learn the Concepts.
Bring Your Ideas to Life 🚀
If you need help with a Laravel project let’s get in touch.
Lucky Media is proud to be recognized as a leading Laravel Development Agency
Technologies

Stay up-to-date
Be updated with all news, products and tips we share!

