Skip to main content

Introduction

Backend App uses Laravel Sanctum for API token authentication. Sanctum provides a lightweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs.

Why Laravel Sanctum?

Laravel Sanctum is included in this project (version 4.0) as specified in composer.json:
composer.json
{
  "require": {
    "php": "^8.2",
    "laravel/framework": "^12.0",
    "laravel/sanctum": "^4.0",
    "laravel/tinker": "^2.10.1"
  }
}
Sanctum offers:
  • Simple token-based authentication for API requests
  • No OAuth complexity - just straightforward API tokens
  • Built-in token management - create, revoke, and manage tokens easily
  • Seamless Laravel integration - works with existing authentication guards

How Authentication Works

1

User Creates Account

Users register through your application and receive credentials (email/password).
2

Generate API Token

After authentication, the user requests an API token via a login endpoint.
3

Include Token in Requests

The client includes the token in the Authorization header for all API requests.
4

Token Validation

Laravel Sanctum validates the token and retrieves the authenticated user.

The Authenticated User Endpoint

The API includes a protected endpoint that returns the currently authenticated user:
routes/api.php
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');
This endpoint:
  • Requires the auth:sanctum middleware
  • Returns the authenticated user’s data
  • Responds with 401 Unauthorized if no valid token is provided

Example Request

curl -X GET https://api.example.com/api/user \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Accept: application/json"

Example Response

{
  "id": 1,
  "institutions_id": 5,
  "rol": "admin",
  "nombre": "Juan",
  "apellido": "Pérez",
  "email": "[email protected]",
  "documento_identidad": "12345678",
  "fecha_nacimiento": "1990-05-15",
  "telefono": "+1234567890",
  "activo": true,
  "email_verified_at": "2024-01-15T10:30:00.000000Z",
  "created_at": "2024-01-10T08:00:00.000000Z",
  "updated_at": "2024-01-15T10:30:00.000000Z"
}
Notice that sensitive fields like password and remember_token are automatically hidden from the response. This is configured in the User model’s $hidden property.

Authentication Configuration

Authentication is configured in config/auth.php:
config/auth.php
'defaults' => [
    'guard' => env('AUTH_GUARD', 'web'),
    'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => env('AUTH_MODEL', App\Models\User::class),
    ],
],
While the default guard is web (session-based), Sanctum provides token-based authentication through the auth:sanctum middleware, which is perfect for API authentication.

User Model

The User model includes the necessary traits and configuration for authentication:
app/Models/User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'institutions_id',
        'rol',
        'nombre',
        'apellido',
        'email',
        'password',
        'documento_identidad',
        'fecha_nacimiento',
        'telefono',
        'activo',
    ];

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

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'activo' => 'boolean'
        ];
    }
}

Next Steps

Laravel Sanctum Setup

Learn how to configure Sanctum and generate API tokens

API Resources

Explore the available API endpoints

Build docs developers (and LLMs) love