Laravel API Auth with Sanctum

Alexandru Dumitru
6 min readApr 12, 2021

Laravel, created by Taylor Otwell, is the most popular PHP framework. But you already know that since you are here. In the following lines we will build an authentication system using sanctum.

I will be using a very simple setup on Windows 10. I find XAMPP the easiest way of starting a server and the best part is that it comes with PHP and MySQL. Another program you need to have installed is Composer. This is a dependency manager for PHP. In order to make http requests you can use Postman or Insomnia… or anything you want. I’ll use Postman.

Getting started

Let’s start by creating a new Laravel 8 application. In your terminal navigate to your projects folder and run:

composer create-project laravel/larave my-awesome-api

This will create a new folder called my-awesome-api.

Now cd into my-awesome-api folder using

cd my-awesome-api 

and serve the application with

php artisan serve

Now if you go to http://127.0.0.1:8000/ in your browser you should see the home page of our app.

This means that everything is working fine so far. Note that we are building an API system, so in the future we are going to delete this page as we don’t need it.

Next step is to connect to the database. As I mentioned in the beginning, I’ll be using XAMPP which means we have MySQL database. I will not cover the creation of the database here.

Let’s name our database laravel_api. Setting up is very easy: just go to your .env file and make sure that the environment variables are defined according to your setup.

If everything is ok we can run:

php artisan migrate

and we should see something like this:

Now let’s install Sanctum. This is very easy and involves three steps:

  1. The actual installation. This is done, like almost all packages, with Composer, running the following command:
composer require laravel/sanctum

2. Publish the Sanctum configuration and migration files. We accomplish this by running:

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

This will place a sanctum.php file in your application’s config directory.

3. Run our database migrations. In this way Sanctum will create a table where API tokens will be stored.

php artisan migrate

Before we start using Sanctum we need to make sure that the User model is using the HasApiTokens trait. Go to app\Models\User.php and add the trait. It should look like this:

Now let’s build the API.

I saw many people using a single controller for the entire authentication part of an application. I personally think that contravenes Single responsability principle from SOLID which says:

A class should only have one reason to change, which means it should only have one responsibility.

A global AuthController will have to register(which means also to store the user) log in and also to log out the user. We are not going to do this. Instead we will create three controllers inside a separate directory and a service class for storing the user.

Register controller

Let’s create the user registration controller.

php artisan make:controller Auth/RegisterController

Inside the app directory we create another directory called Services. Inside this one we create a file UserService.php that looks like this:

This class will handle the user saving process. Now the RegisterController class.

Here we inject the UserService into our constructor and assign it to our $userService property.

In the register method we validate the request data, call the store method from our UserService, passing the validated data from the request. The result is a User object stored in the $user. Next we create the token for the fresh saved user, using the createToken method that is accessible from the HasApiToken trait that we used it in our User model. Then we return the token as a json response.

Now we must define out register route in the routes/api.php file like this:

Route::post('/register', [\App\Http\Controllers\Auth\RegisterController::class, 'register']);

Testing the register with Postman

I also recommend to set a header Accept: application/json in the Headers section in order to receive the errors descriptions more readable.

Hit the send button and the result shoud be something like this:

Now we can use the token to make requests that are protected by the Sanctum authentication middleware.

But before that let’s make the login part.

We generate the LoginController in the same directory as the RegisterController.

php artisan make:controller Auth/LoginController

Our controller will look like this:

Don’t forget about the route

Route::post('/login', [\App\Http\Controllers\Auth\LoginController::class, 'login']);

Test the request with Postman

We now have the token and we can send it as Authorization Bearer header in future api calls.

We have the register part and the login one but we have to also log out from our application. Let’s build this part too.

First the controller:

php artisan make:controller Auth/LogoutController

As you can see, this one is very simple. We just get all the authenticated user’s tokens and delete them.

Now the route for this should be accessible only if the user is logged in. In order to achieve this, we define our route inside a group with the auth:sanctum middleware.

Route::group(['middleware' => 'auth:sanctum'], function () {
Route::post('/logout', [\App\Http\Controllers\Auth\LogoutController::class, 'logout']);
});

Now if we try to make a POST request on this route we get “Unauthenticated” message with the 401 code.

Now let’s make the same api call but with the Authorization header and the token we got from the login call.

We get the “Logged out” message and the 200 status.

With postman you can store the token into an environment variable and use it for the necessary requests.

As you can see, the Sanctum package is very easy to install and use. In the future posts we will build a simple Angular app that will consume this api. Also we will extend this api and add more features to it.

This is my very first article here and I know that my way of writing code (and articles like this) can be improved. Don’t hate me for using XAMPP, but I wanted this setup to be done as quickly and easily as possible.

Thank you for being here!

--

--

Alexandru Dumitru

Web developer with Laravel and Angular and almost 3 years of experience.