Laravel Sanctum API Token Authentication Tutorial with example

Harish Kumar · · 13718 Views

Laravel Sanctum is a popular package for API Token Authentication. There are many other packages available to authenticate the APIs request in Laravel. For example, We are already familiar with Laravel Passport and JWT to authenticate the APIs. 

I have already shared the tutorial for making RESTful APIs using Passport Authentication. The main difference between passport and Sanctum is Passport uses OAuth for authorization. On the other hand, Sanctum produces the API tokens without the complication of OAuth.

Laravel Sanctum Installation

Run the following command in your terminal to install the Laravel Sanctum package:

composer require laravel/sanctum

After successfully install package, we need to publish configuration file with following command:

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

Now run the migration command.

php artisan migrate

Next, if you see the kernel.php, by default, it uses auth:api middleware for making simple token-based API authentication. Because we want to use Sanctum for API authentication, so we need to replace it with auth:sanctum middleware.

//kernel.php

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

`HasApiTokens` trait

To issuing API token, we have to use the HasApiTokens trait in the User model. 

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ...
}

Now we can issue tokens for a user.

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

Laravel Sanctum Usages

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

API Token Issuing

To issue a token, you may use the createToken method. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. 

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

Token Abilities

You may pass an array of string abilities as the second argument to the createToken method:

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

To check the ability of a token, you can use tokenCan  method on a User model object. 

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

Revoking Tokens

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

Hope this post will help you to learn about Laravel Sanctum and how to make API using the Laravel Sanctum package.

1

Please login or create new account to add your comment.

1 comment
Mahdi Pishguy
Mahdi Pishguy ·

Thanks so much

You may also like:

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar