Back to Blog
Lesson 7 of the Intermediate Laravel: Real-World Application Patterns course
LaravelJune 25, 20263 min read

Mastering REST API Authentication with Laravel Sanctum

Learn to secure your Laravel API using Sanctum. We'll cover installation, route configuration, and token generation to authenticate your users effectively.

LaravelAPISanctumAuthenticationPHPbackend

Previously in this course, we explored service-oriented task management to keep our business logic clean and decoupled. Now that our core application logic is structured, it is time to expose that functionality via a secure interface. In this lesson, we will implement token-based authentication using Laravel Sanctum, transforming our application into a robust API.

Understanding API Authentication with Sanctum

When building a stateless API, traditional session-based authentication (which relies on cookies) is often insufficient, especially for mobile apps or third-party integrations. Laravel Sanctum provides a lightweight authentication system that allows you to issue API tokens to users.

Sanctum works by attaching a token to the Authorization header of an incoming request. When the server receives a request, the auth:sanctum middleware intercepts it, verifies the token against the personal_access_tokens table, and identifies the authenticated user.

Installing and Configuring Sanctum

First, install Sanctum via Composer:

Bash
composer require laravel/sanctum

Next, publish the configuration file and run the migrations to create the necessary database tables:

Bash
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Finally, ensure the HasApiTokens trait is added to your User model. This trait provides the methods necessary to issue tokens and verify abilities:

PHP
namespace App\Models;

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

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

Implementing Token Generation

To allow users to authenticate, we need an endpoint that accepts credentials and returns a plain-text token. In a production environment, you would typically handle this in an AuthController.

Here is a concrete example of how to generate a token:

PHP
public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required',
    ]);

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

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

    #6A9955">// Generate the token
    $token = $user->createToken($request->device_name)->plainTextToken;

    return response()->json(['token' => $token], 200);
}

The createToken method returns a NewAccessToken instance. The plainTextToken property is the only time you will see the full token; ensure you return this to the client, as you cannot retrieve it again later.

Configuring API Routes

With the authentication logic in place, we need to protect our routes. Open routes/api.php. Sanctum automatically registers the auth:sanctum middleware, which you can apply to your routes to ensure only authenticated users can access them.

PHP
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });

    Route::apiResource('tasks', TaskController::class);
});

By grouping these routes, any request missing a valid Authorization: Bearer {token} header will receive a 401 Unauthorized response.

Hands-on Exercise

  1. Create a LoginController if you haven't already.
  2. Implement the login method shown above.
  3. Use Postman or curl to send a POST request to your login endpoint.
  4. Take the returned token and use it to access the /api/user endpoint by adding the header: Authorization: Bearer YOUR_TOKEN_HERE.

Common Pitfalls

  • Forgetting the Trait: If you forget to add HasApiTokens to your User model, the createToken method will not exist, leading to a "method not found" error.
  • Returning the Token Object: Never return the entire $token object from your controller. It contains metadata that should not be exposed. Always return the plainTextToken string.
  • Header Mismatch: Always ensure your client is sending the header as Authorization: Bearer {token}. A common mistake is omitting the Bearer prefix.
  • Database Migrations: If you installed Sanctum after your initial database setup, ensure you actually ran php artisan migrate. Without the personal_access_tokens table, authentication will fail silently or throw a query exception.

Recap

We have successfully integrated Sanctum into our project. We installed the package, prepared our User model, implemented a token generation flow, and secured our API routes using middleware. This foundation allows us to move forward with building sophisticated API resources that are both secure and easy to maintain.

Up next: We will explore Resource Controllers and API Responses to ensure our data is transformed consistently before it reaches the client.

Similar Posts