Laravel Sanctum for SPA Authentication: Secure Your SPA Easily

Laravel Sanctum is a simple and lightweight package designed for SPA (Single Page Application) authentication. It offers a seamless way to manage user authentication and protect APIs in a Laravel-based application without the complexities of OAuth.

Professional Laravel developers often choose Laravel Sanctum for SPA authentication due to its flexibility, ease of integration, and ability to work across multiple platforms.

In this blog, we’ll explore how Laravel Sanctum can be used to secure SPAs, covering the setup, implementation, and key benefits it brings to your application’s security. 

What is Laravel Sanctum?

Laravel Sanctum is a lightweight package that simplifies SPA (Single Page Application) security.

It’s designed to protect your Laravel apps without the complexity of traditional OAuth systems. Instead, it uses a straightforward, token-based approach to ensure only authorized users can access specific resources.

Here’s how Laravel Sanctum works:

  • Issuing Tokens: Each user generates a personal access token through a simple API call. These tokens act like secret passwords, allowing users to access specific areas of the app.
  • Securing Requests: Every API request carries the token in the “Authorization” header, helping Laravel Sanctum verify the user’s identity and grant access.
  • Granular Control: You can define specific scopes for each token. For example, you can restrict a user to only update their profile by assigning a limited scope.
  • Effortless Revocation: If a token is lost or misused, it can be revoked instantly, preventing unauthorized access.
  • Seamless Integration: Laravel Sanctum works smoothly with Laravel’s session-based authentication, adding an extra layer of security.

Laravel Sanctum is the go-to solution for building secure SPAs, offering an easy and intuitive way to manage API access while keeping things safe and user-friendly.

Need help implementing Sanctum?

How to Get Started With Laravel Sanctum for SPA Authentication?

Eager to experience Laravel Sanctum’s unparalleled security for your Single Page Applications (SPAs)? Hold onto your coding hats, developers, as we are about to begin the practical journey to implement this solution. Laravel Sanctum’s charm lies in its simplicity, requiring minimal configuration and code changes. Let’s dive into the steps to unlock its potential.

Step 1: Install Sanctum

As we start securing your Single Page Applications (SPAs) with Laravel Sanctum, let’s begin by seamlessly integrating it into your existing project. This initial step, characterized by simplicity and efficiency, sets a solid foundation for robust authentication.

  1. Package Installation. Utilize Composer, the dependency manager, to add Laravel Sanctum to your project:
composer require laravel/sanctum
  1. Configuration Publication. Unlock granular control over Laravel Sanctum’s behavior by publishing its configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. Database Migrations. Execute essential database updates to create tables necessary for Sanctum’s functionality:
php artisan migrate

You’ve successfully incorporated Sanctum into your Laravel project! These foundational steps pave the way for implementing robust SPA authentication. Moving ahead, let’s dive into configuring Laravel Sanctum’s middleware to safeguard your API and ensure exclusive access to authorized users.

Step 2: Configure Cookies (SPA Only)

While Laravel Sanctum benefits in Single Page Applications (SPAs), it offers flexibility beyond stateless tokens. It is for SPAs desiring a stateful authentication experience similar to traditional web applications. This cookie configuration unlocks powerful possibilities.

  1. Enable CORS for Cookie Support. Open up communication pathways. You can do so by ensuring your API allows Cross-Origin Resource Sharing (CORS) with credentials. Within your ‘config/cors.php’ file, set ‘supports_credentials’ to true and define the allowed origins for your SPA.
  2. Configure Session Driver. Laravel Sanctum relies on session handling for cookie-based authentication. Edit your ‘config/session.php’ file and set ‘SESSION_DRIVER’ to either ‘cookie’ or ‘database’ depending on your preference. Remember, cookie sessions may need domain configuration for production environments.
  3. Enable Stateful Middleware. Activate Sanctum’s ‘EnsureFrontendRequestsAreStateful’ middleware within your ‘App\Http\Kernel’ class. This middleware ensures stateful cookie-based authentication for SPA requests.
  4. Send CSRF Cookie. To prevent Cross-Site Request Forgery (CSRF) attacks, your SPA needs to send the Laravel CSRF cookie with API requests. Laravel Sanctum provides a convenient route, ‘/sanctum/csrf-cookie’, accessible through your SPA to retrieve and store the cookie for future requests.
  5. Refresh Cookies Periodically. To maintain active sessions, consider implementing mechanisms in your SPA. It periodically refreshes the session cookie before its expiration. This ensures a seamless user experience without interruptions.

While incorporating cookie configuration, you’ve authorized your SPA with stateful authentication capabilities. Remember, this approach comes with additional considerations compared to stateless tokens. It includes aspects like domain configuration and session management.

Step 3: Enable Authenticated User Access (API, SPA)

With Sanctum firmly integrated into your Laravel project, it’s time to solidify its security measures. It involves enabling authenticated user access, ensuring only authorized individuals can traverse your API’s resources.

  1. Apply Sanctum’s Middleware. Protect your API routes by applying the ‘auth:sanctum’ middleware within your ‘routes/api.php’ file. This middleware acts as a vigilant gatekeeper, verifying user authentication before granting access to protected routes.
// Example usage in routes/api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
  1. Utilize Laravel’s Authentication Middleware. Leverage Laravel’s built-in authentication middleware for SPA routes, as Sanctum seamlessly integrates with existing session authentication. Apply middleware like ‘auth’ or ‘guest’ as needed for your application’s logic.

With this configuration, you’ve built walls of protection around your API. This will benefit you in ensuring only authorized users can access its valuable resources. Sanctum’s versatility empowers you to tailor authentication approaches for both API-only and SPA scenarios, catering to diverse application needs.

Step 4: Implement SPA Login and Token Storage

Now that your API is shielded by the power of Sanctum’s authentication, it’s time to equip your Single Page Application (SPA). We’ll incorporate tools to acquire and store these precious tokens. It will enable your users to seamlessly access the protected resources your API offers.

  1. Design Login Interface. Build a user-friendly login interface within your SPA where users can enter their credentials. This can be a simple form or utilize existing authentication libraries for enhanced security.
  2. Send Login Request. Upon login, build an API request to your Laravel application’s endpoint responsible for token generation. This endpoint typically resides in an ‘api/’ route and accepts user credentials for verification.
  3. Process Response and Extract Token. Once your SPA receives the response from the token generation endpoint, create the response to extract the newly generated API token. Remember to handle error scenarios and inform users in case of unsuccessful login attempts.
  4. Store Token Securely. Securely store the obtained API token within your SPA. Local storage offers a convenient option. But consider encrypting the token for additional protection against malicious attacks.
  5. Include Token in API Requests. Integrate the stored token into your SPA’s subsequent API requests. Send the token within the Authorization header of each request, typically prefixed with the keyword “Bearer”.

By covering these steps your SPA can acquire and manage API tokens securely. This step lays the core for a seamless and secure user experience within your application. Granting authorized access to the valuable resources your API provides.

Step 5: Authenticate API Requests with Tokens

Now that we’ve equipped your SPA to acquire and store API tokens, it’s time to activate Laravel Sanctum’s authentication mechanisms. It is important to ensure that only authorized API requests bearing valid tokens can access your protected resources.

  1. Apply ‘auth:sanctum’ Middleware. Add required authentication for protected API routes by applying the ‘auth:sanctum’ middleware within your ‘routes/api.php’ file. This middleware examines incoming requests and verifies the presence of valid API tokens.
// Example usage in routes/api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
  1. Access Authenticated User. Within your API controllers, retrieve information about the authenticated user using the ‘request->user()’ method. This enables you to personalize responses and tailor API interactions based on user identity and permissions.

Laravel Sanctum is beyond its core functionalities. Explore its additional features to further enhance security and user experience within your application. Customize token expiration times, define token scopes for granular access control, and even design custom middleware to tailor authentication logic to your specific needs.

Which are the Must Have Laravel Sanctum Features for SPA Authentication?

Laravel Sanctum’s arsenal of tools empowers you to build robust and secure Single Page Applications (SPAs). But which features are essential for seamless and reliable SPA authentication? Be ready as we unveil the key Sanctum elements to keep your guardrails secure:

1. CSRF Protection

While using Laravel Sanctum for SPA authentication ensures security, it’s crucial to remember the ever-present threat of Cross-Site Request Forgery (CSRF) attacks. These attacks aim to trick your users’ browsers into performing unauthorized actions on your API. Thankfully, Laravel Sanctum offers robust CSRF protection features to keep your SPA safe.

  1. Enable CSRF Middleware. Within your ‘App\Http\Kernel’ class, add the ‘VerifyCsrfToken’ middleware to your desired application group. This middleware intercepts requests and validates the presence of a valid CSRF token.
protected $middlewareGroups = [
    'web' => [
        // ... other middleware
        App\Http\Middleware\VerifyCsrfToken::class,
    ],
];
  1. Fetch CSRF Cookie. Your SPA needs to send the CSRF token along with API requests. Sanctum provides a dedicated route, ‘/sanctum/csrf-cookie’, accessible through your SPA. Implement logic within your SPA to fetch and store this cookie securely for subsequent API requests.
  2. Include Token in Requests. When making API calls from your SPA, ensure the CSRF token is included within the request headers. Most HTTP client libraries like Axios or Fetch automatically handle this upon receiving the CSRF cookie.

CSRF protection is just one piece of the security puzzle. Remember to explore additional Sanctum features. It must include token expiration times, custom middleware, and granular access control to further enhance your SPA’s security posture.

2. Token Abilities/Scopes

Laravel Sanctum offers a powerful feature called token abilities. It is also known as scopes, which allows you to grant fine-grained control over what users can access within your API. This is like equipping each token with a set of permissions, ensuring users only have access to the resources they need.

  1. Define Abilities. Within your user model or a dedicated ability class, define the different abilities you want to manage. These can be simple actions like “read-user” or more complex operations like “update-post”.
class UserAbility
{
    const READ_USER = 'read-user';
    const UPDATE_POST = 'update-post';
    // ... other abilities
}
  1.  Assign Abilities to Tokens. When generating tokens, associate them with specific abilities. You can do this when users log in or through a dedicated API endpoint.
// Generate token with specific abilities
$token = $user->createToken('My Token', [UserAbility::READ_USER]);
// Generate token with all abilities
$token = $user->createToken('Full Access');

While these features are foundational, the “must-have” list might vary depending on your specific application needs. For tailored advice and implementation expertise, consider consulting a web development company specializing in Laravel security solutions. They can help you leverage Sanctum’s full potential and craft a robust and secure SPA ecosystem.

FAQs About Laravel Sanctum for SPA Authentication

Why use Sanctum?
If you’re building a Single-Page Application (SPA), mobile app, or need basic API token authentication, Laravel Sanctum is the right choice. It’s simple, easy to set up, and offers hassle-free security for your app.
Is Laravel Sanctum stateless or stateful?
Sanctum tokens are stateful. They maintain a session and keep track of the user's state on the server, making them suitable for SPAs, mobile apps, and token-based APIs.
Which is better: Sanctum or Passport?
If your app needs OAuth2 support, go with Laravel Passport. For SPAs, mobile apps, or simple API token authentication, Laravel Sanctum is the better choice because it’s simpler and more lightweight.

Conclusion

Laravel Sanctum is a powerful tool for securing SPAs without adding unnecessary complexity. Its token-based approach simplifies user authentication, offers granular control, and ensures secure API access.

With features like easy token issuance, seamless integration with Laravel’s session authentication, and straightforward token revocation, Sanctum provides a reliable security layer for your apps. Whether you’re building a small project or scaling up, Laravel Sanctum makes it easy to manage user access and protect your resources.

Give it a try in your next SPA to experience a hassle-free, secure, and user-friendly authentication process. And if you need professional help, hire our Laravel experts for the best outcomes!

Ensure advanced security solutions for your Laravel application!

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment