API Authentication with Laravel Sanctum

I had a hard time finding a simple documentation on authentication when I started developing in Laravel. The guides available were most of the time messy and confusing.

Many guides focused on creating the whole thing – controllers, models, migrations and what not! The problem with this approach is that people get stuck on creating stuff not really required to understand the API authentication mechanism.

The API authentication mechanism using Sanctum is very simple.

Sanctum is an authentication package, mainly used for securing API calls, and calls from mobile apps and SPA (Single Page Applications).

API authentication in Laravel Sanctum allows users to authenticate themselves and access protected routes on your API.

This is commonly used for single-page applications or mobile applications that need to access your API.

To enable API authentication in Laravel Sanctum, you will first need to install the Sanctum package using Composer:

composer require laravel/sanctum

Once the package is installed, you will need to run the sanctum:install Artisan command, which will create the necessary tables and configure your application to use Sanctum.

Next, you will need to add the HasApiTokens trait to your App\User model. This trait provides the necessary methods for managing API tokens for your users:

<?php

namespace App;

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens;
}

To authenticate a user and generate an API token, you can use the createToken method provided by the HasApiTokens trait.

This method accepts the name of the token as its only argument, and it returns a Token instance:

<?php
$user = User::first();

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

Once you have generated an API token for a user, you can use it to authenticate the user and access protected routes on your API.

To do this, you will need to include the Authorization header with the value Bearer in your API requests:

axios.get('/api/user', {
    headers: {
        'Authorization': 'Bearer <token>'
    }
});

In your Laravel application, you can protect your routes by using the auth:sanctum middleware:

Route::middleware('auth:sanctum')->get('/api/user', function () {
    return Auth::user();
});

This will ensure that only authenticated users with a valid API token can access the route.

You can also use the can method on the user model to check if a user has a specific token:

if ($user->can('my-token')) {
    // The user has the "my-token" token
}

So this is how you can use Sanctum and manage API token for your users.

I have not created dummy controllers, models for this code. This example is just to show you the basic steps you will need to perform with Sanctum.