Laravel: User Authentication & API Token

Laravel is a popular PHP framework that offers many features for web development, such as routing, templating, database abstraction, testing, validation, and more. One of the most important features of any web application is authentication: how to verify the identity of users and grant them access to certain resources or functionalities.

Laravel provides several ways to handle authentication, such as Laravel UI (the default scaffolding), Laravel Jetstream (a starter kit with Inertia.js or Livewire), Laravel Fortify (a headless authentication backend), Laravel Passport (an OAuth2 server implementation), and Laravel Sanctum (a simple authentication system for SPAs, mobile apps, and token-based APIs).

In this blog post, we will focus on Laravel Sanctum and how it can help us authenticate our users in different scenarios. We will also see some examples of how to use Sanctum in our Laravel projects.

What is Laravel Sanctum?

Laravel Sanctum is a package that provides a lightweight authentication system for SPAs (single page applications), mobile applications, and simple token-based APIs. It allows users to create multiple API tokens for their account, which they can use to access our application. The tokens can have scopes that specify which actions they are allowed to perform.

Sanctum also offers a way to authenticate SPAs that need to communicate with a Laravel-powered API. For this feature, Sanctum does not use tokens at all. Instead, it uses Laravel’s built-in cookie-based session authentication services. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.

Sanctum is inspired by GitHub and other applications that issue “personal access tokens” for their users. It is designed to be simple and easy to use without the complexity of OAuth2.

How to install Laravel Sanctum?

The most recent versions of Laravel already include Laravel Sanctum by default. However, if your application’s composer.json file does not include laravel/sanctum , you can install it by running:

composer require laravel/sanctum

Then you need to publish the Sanctum configuration and migration files by running:

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

The configuration file will be placed in your config directory and the migration file will create a table called personal_access_tokens in your database.

Next, you need to run the migration by running:

php artisan migrate

Finally, you need to add the HasApiTokens trait to your User model so that you can issue tokens for your users:

<?php

namespace App\Models;

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

class User extends Authenticatable
{
  use HasApiTokens , Notifiable;
  
  // ...
}

That’s it! You are ready to use Sanctum in your application.

How to use API Token Authentication with Sanctum?

API Token Authentication is useful when you want to authenticate requests from third-party clients or services that need access to your API endpoints. For example, you may have a mobile app or a desktop app that communicates with your backend via HTTP requests.

To use API Token Authentication with Sanctum , you need to do three things:

1) Issue an API token for your user.
2) Protect your routes with sanctum middleware.
3) Include the token in the Authorization header of your requests.

Issuing an API token

To issue an API token for your user , you can use the createToken method on your User model . This method accepts two arguments: a name for the token and an optional array of scopes . The name can be anything that helps you identify the token later , such as “Mobile App” or “Desktop App”. The scopes are strings that define what actions the token can perform , such as “view-posts” or “create-posts”. You can define your own scopes according to your needs .

The createToken method returns an instance of PersonalAccessToken , which has a plainTextToken property that contains the actual token value . You should store this value securely on your client side and never expose it publicly .

For example, let’s say we want to create a token for a user with the email john@example.com, and give it only read access:

$user = User::where('email', 'john@example.com')->first();

$token = $user->createToken('read-only-token', ['read']);

The createToken method returns a PersonalAccessTokenResult instance that contains two properties: accessToken and plainTextToken. The accessToken is an instance of PersonalAccessToken, which represents the token model stored in the database. The plainTextToken is a string that contains both the token ID and value separated by a pipe (|). You should store this value securely or send it back as a response to your client.

For example:

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

Using an API Token

To use an API token to authenticate your requests, you need to pass it as a bearer token in the Authorization header of your request. For example:

GET /api/user HTTP/1.1
Host: example.com
Authorization: Bearer 6|yJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImQyZjMwN2E4YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI5ZjMwNzA3YmI9fQ...
Accept: application/json

To protect your routes from unauthorized access, you can use the auth:sanctum middleware on your routes or controllers. For example:

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

If you want to check if a token has a specific ability or scope, you can use the $request->user()->tokenCan() method inside your route closure or controller method. For example:

Route::middleware('auth:sanctum')->get('/api/posts', function (Request $request) {
  if ($request->user()->tokenCan('read')) {
    return Post::all();
  }
  
  abort(403);
});

Conclusion

In this post, I showed you how to issue an API token using Laravel Sanctum and use it to authenticate your requests.

Scroll to Top