Laravel 11 for Beginners: API Routes with Laravel Sanctum

Arlind Musliu Portrait
Arlind Musliu

July 30, 2024 · 5 min read · 150 views

Laravel Logo Post

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, 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.

laravel pipelines

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

  1. Stateful: This means the server needs to keep track of the user's session state, typically in a session store or database.

  2. 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.

  3. 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.

  4. 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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

laravel pipelines

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

Generating Tokens

We need to create an AuthController that will handle the token generation for our users. First, create the controller using the command:

php artisan make:controller API/AuthController

Then, open the newly created AuthController located at app/Http/Controllers/API/AuthController.php and add the following code:

<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    // Method to handle user authentication and token generation
    public function generateToken(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        $token = $user->createToken('my-app-token')->plainTextToken;

        return response()->json(['token' => $token], 200);
    }

    // Method to handle user logout and token revocation
    public function logout(Request $request)
    {
		// Revoke all tokens...
		$request->user()->tokens()->delete();

		// // Revoke the current token
		$request->user()->currentAccessToken()->delete();

		return response()->json(['message' => 'You have been successfully logged out.'], 200);
    }
}

This method validates the user's credentials and then generates a new token with the specified ability. The /auth/token route is open for unauthenticated users, while the /auth/logout route is protected by the auth:sanctum middleware, ensuring that only authenticated users can access it. Let's do that now.

Protecting Routes with Middleware

Sanctum provides middleware that can be applied to your API routes to protect them. This ensures 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.

<?php
use App\Http\Controllers\API\UserController;
use App\Http\Controllers\API\PostController;
use App\Http\Controllers\API\AuthController;

// Public routes
Route::post('/auth/token', [AuthController::class, 'generateToken']);

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']);

    // Logout route
    Route::post('/auth/logout', [AuthController::class, 'logout']);
});

With this middleware in place, only authenticated requests with a valid Sanctum token will be able to access the protected routes. We created these routes in a previous article named Laravel 11 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 utilizing Sanctum, you can ensure 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

  1. Laravel 11 for Beginners: CSRF Protection explained

  2. Laravel 11 for Beginners: Using Helpers PHP functions

  3. Laravel 11 for Beginners: Using Custom and Built-in Commands

This article is part of our series Laravel 11 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 Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!