API Authentication using Laravel Sanctum — Laravel 8
For web developers, it’s important for us to authenticates our users via API Request. In Laravel itself, besides its full-stack development, we have many options on how to authenticate the requests. For example, we have the Laravel Passport package to do the authentication and OAuth processes. But, if you don’t want to use the OAuth feature that Passport offers, then the Laravel Sanctum may be a choice for you.
What is Laravel Sanctum?
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs (https://laravel.com/docs/8.x/sanctum)
Yes, in Sanctum, we have two options here. The first is the API Token Authentication, and the second is SPA Authentication. There is another authentication such as Mobile Applications, but this authentication has a similar process to API Token Authentication.
So the next question is, what are the differences between the API Token and SPA Authentication? The API Token Authentication uses a Token that your client/front-end must issue first before sent any requests to the server. Your client gets the Token via the /login routes, then every next request, the token must be included in the Authorization header as a Bearer token. Pretty simple right?
The SPA Authentication, on the other hand, doesn’t need any tokens. Instead, it uses Laravel’s built-in cookie based session authentication services. When we’re using this type of authentication, we don’t need to include the Authorization Bearer header on every request. It’s useful when you’re building the first-party SPA, that your front-end project can be inside your Laravel project or an entirely separate repository/project.
So in this article, I’ll show you how to build the API Token Authentication using Sanctum. It’s a very simple project, and of course, you can see the complete repository at the bottom of this article.
Content Overview
- Project & Sanctum Installation
- Authentication Routes
- Let’s Test It!
#1 Project & Sanctum Installation
Okay, the first one, let’s create a fresh Laravel project.
composer create-project laravel/laravel --prefer-dist laravel-sanctum
After installation succeeds, install the Laravel Sanctum package.
composer require laravel/sanctum
Then publish the Sanctum configuration and migration files. The Sanctum configuration file will be placed inside your config directory.
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Next, migrate your database. Don’t forget to adjust your database configuration inside your .env file.
php artisan migrate
One very last thing, your User model needs to use the Laravel\Sanctum\HasApiTokens trait, so that we can issue the token with createToken() method.
#2 Authentication Routes
It’s time for the important part. Before we continue on building the authentication routes, it’s better if we’re creating an API Response trait so that we can return a consistent response in a simple way. Let’s create a file inside App\Traits\ApiResponser.php. Feel free if you want to make any changes to the trait.
First, let’s start with the basic endpoint scaffolding. Open your routes/api.php and modify it.
On lines 19 and 20, we’ll implement the register and login functions. And on lines 23–28, we protect the routes with the “auth:sanctum” middleware so only authenticated users can access them. On line 24, we then return an authenticated user using auth()->user().
Create a new controller inside App\Http\Controllers\AuthController.php and modify it.
On the register() function, we have very simple logic. First, we validate the request that the client sends, then we create a new user. Last thing to do we send back an API Token to the clients. On lines 30 and 46 is the way on how we can create a token for the users. We need a string parameter passed on the createToken() function that we can type it with anything. Just a tip from me, you can pass a string parameters with the device name such as Iphone12, Macbook, etc.
For the logout() function itself, we can just revoke the token. Then the token will automatically invalid if the client requested with revoked/deleted token.
#3 Let’s Test It!
First, let’s try the registration step.

After the registration succeeds, we’ll receive a token. Then, we’ll make another request to the /api/me to test if the endpoint will properly return a correct authenticated user. Don’t forget, you need the header Authorization with Bearer token.

As you can see from the result above, the endpoint sends back a correct authenticated user. Try to remove the token, or make it an invalid token so that you’ll become unauthenticated.
It’s a simple tutorial on how we use Sanctum for API Authentication. But, as you know, Sanctum has some features too, for example, you can easily manage and assign token abilities by using this command:
return $user->createToken('token-name', ['server:update'])->plainTextToken;
And check the user’s token abilities with:
if ($user->tokenCan('server:update')) {
//
}
That’s it on how we can use the Sanctum to do the API Authentication process. I hope this article can be a good reference for you and, see you next time.