Laravel Sanctum | Fonseka Innovations
Laravel Sanctum

This article will helps understand Laravel Sanctum and how to get started with it.

What is Laravel Sanctum?

It is a featherweight authentication package from Laravel.

Sanctum can ensure requests to be having a valid token or a valid session. Which makes the application to handle both stateful and stateless requests.

Not only that but also, Sanctum makes it much easier to develop and manage the token-based authentications.

What is Stateless and Stateful?

Stateless vs Stateful | Fonseka Innovations
Stateless vs Stateful

Stateless means authentication is done on every request. For this purpose, tokens or sessions are used to communicate with the servers. For example,

HTTP requests are stateless.

And then, stateful means the server keeps a session with the initial requests. On the positive side, this makes it much faster and flexible to authenticate.

If you are wondering is this the same as Laravel Airlock? Well, it was, due to trademark disputes it got renamed to Laravel Sanctum.

Taylor Otwell – Laravel Airlock renamed

Laravel Sanctum got released with the latest Laravel release. (Read More about Laravel 7)

Main Two Features

Token Protection | Fonseka Innovations
Token Protection

API Tokens

Sanctum solves one of the main problems in dealing with the complications of OAuth authentication.

Not to mention, this feature is a bit similar to GitHub's access tokens.

Sanctum can generate and manage tokens by the user level. Also, these tokens can be used to grant or revoke, users with different scopes and permissions at any time.

These API tokens are saved in a single database table and then used to authenticate incoming requests. And, these requests are accessed via the 'Authorization' header.

SPA Authentication

Sanctum offers a simple way to authenticate single-page applications (SPAs) that requires an API. Most preferably a Laravel powered API.

In order to handle these requests, Sanctum uses Laravel's built-in cookie-based session authentication services. This service includes CSRF and session protections.

Sanctum only attempts to authenticate using cookies when the incoming request originates from your SPA frontend.

Business Applications with Laravel Sanctum

Business Applications for Laravel Sanctum | Fonseka Innovations
Business Applications for Laravel Sanctum

At present, many organisations are incorporating web and mobile applications. As a result of it, the number of connections to the application increases.

Not just that, security is equally important when having an API.

Therefore, to handle multiple users in a Management Systems or Application Program Interface (API) requires proper OAuth connectivity.

On the negative side, developing an API with OAuth is not an easy task. In fact, many developers are struggling to develop a good token-based authentication system.

Generally speaking, most developers tend to increase performance by lowering response time. But not considering the security behind it.

In the long run, this will negatively impact the application. Therefore, sooner or later, you will need to consider the security behind the API.

Startup Guide

To start off with the guide, you can follow the installation guide from the Laravel Docs.

But here is the basic understanding of what needs to happen to get started with Sanctum.

Prerequisites

Sanctum Installation

  • To begin the installation, install Laravel Sanctum from ‘composer’.
composer require laravel/sanctum
  • Then, Publish the vendor service providers to the project.
php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

Once that's done, run the migrate command to create all the token tables in your database.

php artisan migrate

In addition to that, Laravel provides us with ‘auth:api’ middleware. Which is for making simple token-based API authentication.

This comes out of the box from Laravel.

Once that's all set.

Additionally, you can add the below lines to the Kernel file. Only if you are in need to use Sanctum for API authentication. Hence, this authentication enables the usage of the 'auth:sanctum' routes.


use LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful;

'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],

Done, and now you can use Sanctum in your project.

Using Laravel Sanctum with Passport

Laravel Passport is an authentication plugin similar to Sanctum. However, Laravel Passport provides a full OAuth2 server implementation for the application. Besides, Passport is built on top of the League OAuth2 server. (Read more about Laravel Passport)

The main difference between Sanctum and Passport is,

Passport provides a full OAuth2 server implementation for the application, and then Sanctum provides a simple package to issue API tokens to the users without the complication of OAuth.

Most of the time, we will be using a single guard for the API.

Similarly, you can add another guard in this case, Passport and Sanctum. So you need to include both in the middleware of the routes.

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

Usage of SPA Authentication

Firstly, we need to make a GET request to ‘/sanctum/csrf-cookie’. As a result, this enables the CSRF protection. This does not mean the user will log in once this is done.

Therefore, once the request hits the sanctum/csrf-cookie route, you need to make another request to ‘login’.

API Token Issuing

To issue API tokens, at first, we have to use the 'HasApiTokens' trait in the user model.

use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}

Once it is all set. You can create tokens as shown below. Apart from it, if you are wondering what is HasApiTokens, it is a Trait. (Read More about Trait)

$token = $user->createToken('here-token-name');
return $token->plainTextToken;

Laravel Sanctum provides us with few token abilities, like giving permissions to any tokens.

$user->createToken('token-name', ['post:update']);

The above code is to create the token with the specific permission set. And then to check whether the token has the given ability, we can use ‘tokenCan’ as shown below.

if ($user->tokenCan('post:update')) {
//
}

Revoking Tokens

$user->tokens->each->delete();

Conclusion

In conclusion, Laravel Sanctum is a powerful plugin which was developed by Laravel. This plugin can be used to develop a SPA or to create token-based authentication.

Therefore, if you are seeking to create a new API or to create a SPA. You can use Laravel Sanctum to your advantage. Furthermore, you can use this to connect any application or even to feed data to a WordPress website.

We at Fonseka Innovations can help you with many options to build an API or a SPA. We have built many web and mobile applications that use OAuth.

Additionally, we have used this plugin for many projects we got. Usage of Laravel Sanctum cut down the development time almost by a half.

Apart from it, if you want us to help you upgrade or to maintain your website, any application. Feel free to fill in the form below with your details.

Fonseka Innovations
Fonseka Innovations

References

Tutorial Links

About the author

Leave a Reply