Blog Detail

02

Nov
Laravel Sanctum -  Build Authentication System for APIs cover image

arrow_back Laravel Sanctum - Build Authentication System for APIs

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities/scopes which specify which actions the tokens are allowed to perform.

Why Use Laravel Sanctum?

Laravel Sanctum exists to solve two separate problems. Let’s discuss each before digging deeper into the library.

API Tokens

First, Sanctum is a straightforward package you can utilize to assign API tokens to your users without the complication of OAuth. This feature is encouraged by GitHub and other applications which issue “personal access tokens”. For example, imagine the “account settings” of your application has a screen where a user can generate an API token for their account. You can utilize Sanctum to generate and maintain those tokens. These tokens typically have a very long expiration time (years), but maybe manually withdrawn by the user at any time.
Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the Authorization header which should contain a valid API token.

SPA Authentication

Second, Sanctum exists to offer an uncomplicated way to authenticate single-page applications (SPAs) that require communication with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or it can be a completely separate repository, such as a SPA created employing Vue CLI or a Next.jsapplication.

For this purpose, Sanctum employs Laravel’s built-in cookie-based session authentication services instead of utilizing any tokens. Generally, Sanctum utilizes Laravel’s web authentication guard to perform this. This provides the advantages of CSRF protection, session authentication, and also offers protection against leakage of the authentication credentials via XSS.

Installation

You can install Laravel Sanctum via the Composer package manager:

composer require laravel/sanctum

Next, you should publish the Sanctum configuration and migration files utilizing the vendor:publish Artisan command. The sanctum configuration file will be added to your application’s config directory:

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

Finally, you have to run your database migrations. Sanctum will create one database table in which to store API tokens.

php artisan migrate

You will notice that the personal_tokens table is generated.

Issuing API Tokens

Sanctum enables you to issue API tokens/personal access tokens that may be used to authenticate API requests to your application. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.

To begin issuing tokens for users, you have to add the Laravel\Sanctum\HasApiTokens trait in your User Model.

<?php

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
 use HasApiTokens;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

}

Route authentications

To protect routes so that all incoming requests must be authenticated, you should attach the sanctum authentication guard to your API routes within your routes/api.php file. So here we add sanctum middleware to the routes.

<?php

//import controller
use App\Http\Controllers\AuthenticationController;

//register new user
Route::post('/register', [AuthenticationController::class, 'register']);

//login user
Route::post('/login', [AuthenticationController::class, 'login']);

//using middleware
Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::get('/user-profile', function(Request $request) {
        return auth()->user();
    });
    Route::post('/logout', [AuthenticationController::class, 'logout']);
});

Now open the AuthenticationController. Here we will use the createToken method to issue a token. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. API tokens are hashed utilizing SHA-256 hashing before being stored in your database, but you can access the plain-text value of the token using the plainTextToken property of the NewAccessToken instance. You have to display this value to the user immediately after the token has been created:

<?php

class AuthenticationController extends Controller
{
    //this method adds create user
    public function register(Request $request)
    {
        $attr = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users,email',
            'password' => 'required|string|min:6|confirmed'
        ]);

        $user = User::create([
            'name' => $attr['name'],
            'password' => bcrypt($attr['password']),
            'email' => $attr['email']
        ]);

        return $this->success([
            'token' => $user->createToken('tokens')->plainTextToken
        ]);
    }

    //use this method to login users
    public function login(Request $request)
    {
        $attr = $request->validate([
            'email' => 'required|string|email|',
            'password' => 'required|string|min:6'
        ]);

        if (!Auth::attempt($attr)) {
            return $this->error('Credentials not match', 401);
        }

        return $this->success([
            'token' => auth()->user()->createToken('API Token')->plainTextToken
        ]);
    }

    // this method logout out users by removing tokens
    public function logout()
    {
        auth()->user()->tokens()->delete();

        return [
            'message' => 'Tokens Revoked'
        ];
    }
}

Above in the controller, we make the register() method that creates new validated users. It then generates tokens if registered successfully. The login() function authenticates users and generates access tokens on successful login. Finally, the logout() method removes the user’s session.

In the above tutorial, we reviewed Laravel Sanctum and API Authentication with Laravel Sanctum. I hope this tutorial will help you, and you can utilize this knowledge to build powerful APIs. For more information, You can see its detailed documentation here.

Published at : 02-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project