Bobcares

Secure Your Laravel SPA with Sanctum Authentication

by | Jun 6, 2024

Learn how to secure Laravel SPA with Sanctum Authentication. Our Laravel Support team is here to help you with your questions and concerns.

Secure Your Laravel SPA with Sanctum Authentication

Secure Your Laravel SPA with Sanctum AuthenticationDid you know we can simplify implementing user authentication in a Single Page Application built with Laravel by using Laravel Sanctum?

Sanctum uses Laravel’s session-based authentication with cookies, provides CSRF protection, and prevents credential leaks through XSS vulnerabilities.

The Process Flow

  • The SPA fetches a CSRF token from a Sanctum endpoint. This token is included in subsequent requests for CSRF protection.
  • The SPA sends a login request to the standard Laravel login endpoint with the username and password.
  • After successful login, Laravel issues a cookie containing the user’s session data.
  • Subsequent requests from the SPA to the Laravel API include the session cookie, allowing continued user access throughout the session.

Key Points to Consider

Sanctum relies on cookie-based authentication, so our SPA and Laravel backend must reside on the same top-level domain (or subdomains) for it to function correctly.

Sanctum requires minimal configuration. We have to enable the necessary middleware and adjust CORS settings for your application’s specific needs.

Advantages of Using Sanctum

  • Sanctum is easy to integrate into existing Laravel projects.
  • It uses Laravel’s built-in security features like CSRF protection and session management.
  • Sanctum supports generating API tokens for extended access needs.

What is Laravel Sanctum?

Building secure Single Page Applications (SPAs) can be complex, but Laravel Sanctum simplifies the process by providing a token-based approach to API security. Sanctum acts as an API bouncer, ensuring only authorized users gain access.

Here are some of the key features of Sanctum:

  • Users generate their own personal access tokens through a simple API call. Each token can have specific permissions, such as read-only or full access.
  • These tokens act as secret passwords for your API. Each request carries the token in its “Authorization” header. This allows Laravel Sanctum to verify the user’s identity and grant access.
  • Sanctum lets us define token scopes, restricting users to specific actions within our API.
  • Sanctum lets us revoke lost tokens, locking out unauthorized access.
  • Sanctum works seamlessly with Laravel’s existing session authentication, adding an extra layer of protection.

How to Get Started with Laravel Sanctum for SPA Authentication

We can secure SPA with Laravel Sanctum with these steps:

  1. First, integrate Sanctum into the existing project using Composer:

    composer require laravel/sanctum

  2. Then, publish Sanctum’s configuration file:

    php artisan vendor:publish –provider="Laravel\Sanctum\SanctumServiceProvider"

  3. Now, run the necessary database migrations:

    php artisan migrate

  4. Next, enable CORS for cookie support by ensuring the API allows Cross-Origin Resource Sharing with credentials. So, set `supports_credentials` to `true` in the `config/cors.php` file.
  5. Then, configure the session driver in `config/session.php` and set `SESSION_DRIVER` to either `cookie` or `database`.
  6. Next, enable Sanctum’s `EnsureFrontendRequestsAreStateful` middleware in the `App\Http\Kernel` class.
  7. Now, retrieve the CSRF cookie with the SPA by accessing the `/sanctum/csrf-cookie` route.
  8. After that, protect the API routes by applying the `auth:sanctum` middleware in the `routes/api.php` file:

    Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
    });

    We can use Laravel’s built-in authentication middleware for SPA routes.

  9. Now, we can design a user-friendly login interface within the SPA.
  10. Additionally, send a login request to the Laravel application’s endpoint responsible for token generation.
  11. Then, process the response and extract the generated API token.
  12. Now, it is time to store the token securely within the SPA.
  13. We have to include the token in the SPA’s subsequent API requests in the Authorization header.
  14. Then, apply the `auth:sanctum` middleware to the protected API routes in `routes/api.php`.
  15. We can retrieve information about the authenticated user within the API controllers using the `request->user()` method.

Laravel Sanctum offers a robust and developer-friendly approach to SPA authentication. By following these steps, we can secure the SPAs effectively.

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

In brief, our Support Experts demonstrated how to secure Laravel SPA with Sanctum Authentication.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.