Skip to content

API Token Authentication

Token-based authentication is generally not recommended for Single Page Applications (SPAs). However, it can be quite useful in specific scenarios, such as mobile or desktop applications, where maintaining a session-based authentication system is less feasible.

Configuration

To enable API token-based authentication in your Nuxt 3 application, you need to configure the laravelSanctum.authMode property to use token in your nuxt.config.ts file:

javascript
export default defineNuxtConfig({
    laravelSanctum: {
        apiUrl: 'http://laravel-api.test', // Your Laravel API URL
        authMode: 'token',
    },
});

How It Works

Once token-based authentication is enabled, you can authenticate users by sending their credentials to the specified login endpoint. Here's an example of how you can perform this operation:

javascript
const { login } = useSanctum();

const credentials = {
    email: "john@doe.com",
    password: "password",
    remember: true,
};

await login(credentials);

When the login method is invoked, the credentials are sent to the backend API. Upon successful authentication, the API will return a plain token. This token is then stored by the module and is automatically included in the Authorization header for all subsequent requests, ensuring that authenticated API calls are properly authorized.

Laravel Configuration

To support token-based authentication on the backend, your Laravel API needs to have appropriate login and logout routes defined in your api.php routes file:

php
Route::post('/login', [TokenAuthenticationController::class, 'store'])
    ->middleware(['guest']);

Route::post('/logout', [TokenAuthenticationController::class, 'destroy'])
    ->middleware(['auth:sanctum']);

Here is the example code in the TokenAuthenticationController:

php
<?php

namespace App\Http\Controllers;

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

class TokenAuthenticationController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

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

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

        return [
            'token' => $user->createToken('token-name')->plainTextToken
        ];
    }

    public function destroy(Request $request)
    {
        // Revoke all tokens...
        // $request->user()->tokens()->delete();

        // Revoke the token that was used to authenticate the current request...
        $request->user()->currentAccessToken()->delete();
    }
}

Key Considerations:

  1. CSRF Protection: Ensure that the API requests are not originating from a domain listed in the SANCTUM_STATEFUL_DOMAINS environment variable. If they are, you may encounter a CSRF mismatch error, which occurs because Laravel Sanctum is expecting session-based authentication for stateful domains.

  2. Token Format: The login endpoint should return a JSON response containing a token key. The token should be a plain string, representing the user's access token. Here's an example of the expected response format:

json
{
    "token": "<plain_token_value>"
}

By following this setup, your Nuxt 3 application will be able to authenticate users using API tokens, and the module will handle storing and sending the token with each API request.

For more detailed information and further configuration options, you can refer to the official Laravel documentation on API Token Authentication.