Authentication process using Laravel Sanctum

Back-End Dev Note March 23, 2023

Hi everyone! I am Ericka Fiona Payuyo, a student from the University of Santo Tomas and is currently a PHP Developer Intern at Commude PH. For this blog, I will walk you through an authentication process using Laravel Sanctum.

 

Laravel Sanctum mainly imparts authentication on applications by API tokens and cookie-based
session for single page applications. These tokens are stored in a database table which are used to authenticate requests by validating the token.

 

Let’s start with the set-up of this authentication process. First will be the installation of the Laravel Sanctum to the application. Composer is needed to install the package. The set-up is installed using the configuration:

 

composer require laravel/sanctum

 

Once installed, the configuration of Laravel sanctum would be embedded to the application and files such as composer.json will be updated. With that, the application will have a built-in authentication process provided by sanctum. If we look at the database, there would be a separate table for personal access tokens already.

 

 

Another thing is that in the User model, the HasApiTokens function of Laravel sanctum is already implemented.

 

 

For the authentication of API requests, tokens are issued using Laravel Sanctum. To do this, there is a createToken method to generate personal access tokens unique for each user.

 

 

After creating, there will be a personal access token data that will be created and reflected on the database. And there, we have created our first API token for the users using Laravel sanctum.

 

 

Next up is the implementation of Laravel Sanctum on the single page application authentication. To implement this, the Kernel file should be configured. This means that adding the middleware of Sanctum to the middleware group of API is needed.

 

 

Lastly, the routes should be declared in the routes/api.php to protect the route and the sanctum authentication guard would be attached.