Laravel API Authentication with Sanctum

Lesson 36 of 50

72%
1. What Is Laravel Sanctum?

Laravel Sanctum is a Laravel package used to authenticate users for APIs and single-page applications.

Sanctum commonly supports two authentication approaches:

  • API tokens: Users send a personal access token with API requests.
  • SPA authentication: A first-party frontend uses Laravel's cookie-based session authentication and CSRF protection.

Sanctum is useful for:

  • Mobile applications
  • React and Vue applications
  • Student management APIs
  • Admin dashboards
  • Personal access token authentication

In this lesson, we will learn the basic token-based authentication workflow.

2. Install and Configure Sanctum

For supported modern Laravel versions, you can use the following command to install API scaffolding, including Sanctum:

php artisan install:api

In existing projects or versions where this command is unavailable, install Sanctum using Composer:

composer require laravel/sanctum

Follow the installation instructions for your Laravel version to publish any required configuration or migration files.

Run migrations when required:

php artisan migrate

Sanctum's personal access tokens are stored in the personal_access_tokens table.

3. Prepare the User Model

To create personal access tokens, the authenticatable model must use Sanctum's HasApiTokens trait.

Open app/Models/User.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];
}

The HasApiTokens trait provides methods such as createToken() for issuing API tokens.

Keep your existing model configuration and add the trait rather than replacing unrelated project settings.

4. Create a Login API

The login endpoint verifies the user's credentials. If they are correct, it creates a token and returns it to the client.

Create a controller:

php artisan make:controller Api/AuthController

Example controller 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
{
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $user = User::where(
            'email',
            $credentials['email']
        )->first();

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

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

        return response()->json([
            'message' => 'Login successful',
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
            ],
        ]);
    }
}

This example assumes users have already been registered and their passwords are stored as secure hashes.

5. Define API Routes

Open routes/api.php and define the login route and a protected profile route.

use App\Http\Controllers\Api\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/login', [
    AuthController::class,
    'login'
]);

Route::middleware('auth:sanctum')->get(
    '/profile',
    function (Request $request) {
        return response()->json([
            'user' => $request->user(),
        ]);
    }
);

Example endpoints:

POST /api/login
GET  /api/profile

The login endpoint is public. The profile endpoint requires a valid authenticated request.

In modern Laravel projects, API routing may need to be enabled or installed first. Follow the setup steps for your Laravel version if routes/api.php does not exist.

6. Send a Token with an API Request

After login, the client receives a token. For subsequent requests, send it in the Authorization header.

Authorization: Bearer YOUR_API_TOKEN
Accept: application/json

Example request using JavaScript:

fetch('/api/profile', {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer YOUR_API_TOKEN'
    }
})
.then(response => {
    if (!response.ok) {
        throw new Error('Request failed: ' + response.status);
    }

    return response.json();
})
.then(data => {
    console.log(data);
})
.catch(error => {
    console.error(error);
});

Replace YOUR_API_TOKEN with the token returned by your login endpoint. In a real application, use your API's full URL when the frontend and backend run on different origins.

7. Protect Routes and Revoke Tokens

Use the auth:sanctum middleware to protect routes that require authentication.

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/dashboard', function (Request $request) {
        return response()->json([
            'message' => 'Welcome to your dashboard',
            'user_id' => $request->user()->id,
        ]);
    });
});

To log out the current token-based session, revoke the token used for the current request.

Route::middleware('auth:sanctum')->post(
    '/logout',
    function (Request $request) {
        $request->user()
            ->currentAccessToken()
            ?->delete();

        return response()->json([
            'message' => 'Logged out successfully',
        ]);
    }
);

This logout example is intended for personal access token authentication. Cookie-based SPA authentication has a different session logout flow.

8. Sanctum Security Best Practices
  • Always use HTTPS in production.
  • Store passwords using Laravel's password hashing tools.
  • Never expose tokens in URLs or public logs.
  • Keep tokens out of source control.
  • Revoke tokens when users log out or access must be removed.
  • Use token abilities when you need to restrict token permissions.
  • Validate incoming request data.
  • Use policies or gates to control access to protected records.
  • Configure cookie, session, CORS, and CSRF protections correctly for SPA authentication.

Remember:

Authentication confirms who the user is. Authorization determines what the user is allowed to do.

9. Practice Assignment

Build a simple token-authenticated Student API.

  1. Install and configure Laravel Sanctum.
  2. Add the HasApiTokens trait to the User model.
  3. Create a login endpoint that validates email and password.
  4. Return a personal access token after successful login.
  5. Create a protected /api/profile endpoint.
  6. Test the login and profile endpoints in Postman.
  7. Create a logout endpoint that revokes the current token.

Bonus Task:

Create a protected /api/students endpoint that returns student records only to authenticated users.

Quick Quiz

1. What is Laravel Sanctum used for?




2. Which trait enables personal access token creation?




3. Which middleware protects routes using Sanctum authentication?