API Authentication using Laravel Sanctum — Laravel 8

Cerwyn Cahyono
Jan 17 · 4 min read
Image for post
Image for post
Photo by Chepe Nicoli on Unsplash

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.

Image for post
Image for post
Photo by Dayne Topkin on Unsplash

Content Overview

  • Project & Sanctum Installation
  • Authentication Routes
  • Let’s Test It!

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.

App\Models\User.php

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.

App\Traits\ApiResponser.php

First, let’s start with the basic endpoint scaffolding. Open your routes/api.php and modify it.

routes/api.php

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.

First, let’s try the registration step.

Image for post
Image for post
Image 1. Registration

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.

Image for post
Image for post
Image 2. Authenticated User

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.

References

The Startup

Medium's largest active publication, followed by +775K people. Follow to join our community.

Cerwyn Cahyono

Written by

PHP/Backend Engineer at Undercurrent Capital Pte Ltd — Data Science Enthusiast

The Startup

Medium's largest active publication, followed by +775K people. Follow to join our community.

Cerwyn Cahyono

Written by

PHP/Backend Engineer at Undercurrent Capital Pte Ltd — Data Science Enthusiast

The Startup

Medium's largest active publication, followed by +775K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store