API Authentication using Laravel Sanctum - TechvBlogs

API Authentication using Laravel Sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs, mobile applications, and simple, token-based APIs.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

3 years ago

TechvBlogs - Google News

What is Laravel Sanctum?

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. Here are some reasons you might want to choose Sanctum over Passport:

  1. Passport is implemented with OAuth2 authentication. If you are not using that, then Sanctum is your go-to for issuing API tokens.
  2. Sanctum is a featherweight, meaning it is light and simple to implement.
  3. Sanctum works with SPAs (Single Page Applications like Vue, Angular, and React) and supports mobile application authentication.

Getting started

First, open Terminal and run the following command to create a fresh laravel project:

composer create-project --prefer-dist laravel/laravel larasanctum-api

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new larasanctum-api

Setup Database Detail

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

Read Also: Firebase Push Notification Laravel Tutorial

Installation and Setup

Now would be a good time to start the Laravel application to make sure everything is working as expected:

cd larasanctum-api
php artisan serve

Let’s add Laravel Sanctum to it. First, we need to install Laravel Sanctum into our application using Composer:

composer require laravel/sanctum

Next, we'll publish Laravel Sanctum configuration and migration files using the following command:

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

Now, run the database migrations:

php artisan migrate

To use tokens for users, add the HasApiTokens trait inside the User model.

Open the app/Models/User.php file and add the following modifications:

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
}

Setup Middleware

Edit your app/Http/Kernel.php file to add Sanctum’s middleware into your API middleware group.

'api' => [
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
],

Building the API

Let’s start with registering for an account. In your terminal create the controller responsible for authentication by running the following Artisan command:

php artisan make:controller AuthController

Now open the routes/api.php file to create the route for registering a user:

use App\Http\Controllers\AuthController;

Route::post('/register',[AuthController::class,'register']);

Open app/Http/Controllers/AuthController.php and create a method to register a user:

use Illuminate\Support\Facades\Hash;

public function register(Request $request){
    $post_data = $request->validate([
        'name'=>'required|string',
        'email'=>'required|string|email|unique:users',
        'password'=>'required|min:8'
    ]);

    $user = User::create([
        'name' => $post_data['name'],
        'email' => $post_data['email'],
        'password' => Hash::make($post_data['password']),
    ]);

    $token = $user->createToken('authToken')->plainTextToken;

    return response()->json([
        'access_token' => $token,
        'token_type' => 'Bearer',
    ]);
}

First, we validate the incoming request to make sure all required variables are present. Then we persist the supplied details into the database. Once a user has been created, we create a new personal access token for them using the createToken() method and give the token a name of authToken. Because createToken() will return an instance of Laravel\Sanctum\NewAccessToken, we call the plainTextToken property on the instance to access the plain-text value of the token. Finally, we return a JSON response containing the generated token as well as the type of the token.

Next, create a route for the login user, open routes/api.php, and update the following code into a file:

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

Now add login method to AuthController

use Illuminate\Support\Facades\Auth;

public function login(Request $request){
    if (!\Auth::attempt($request->only('email', 'password'))) {
        return response()->json([
            'message' => 'Invalid login details'
        ], 401);
    }

    $user = User::where('email', $request['email'])->firstOrFail();

    $token = $user->createToken('authToken')->plainTextToken;

    return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
    ]);
}

Add the routes that require authentication inside the middleware group. As the login route doesn’t use the authentication middleware, it goes outside the middle group.

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\AuthController;

Route::post('/register',[AuthController::class,'register']);
Route::post('/login', [AuthController::class, 'login']);

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

Now, All sets to go, and Let's test API routes.

Create a new User

API Authentication using Laravel SanctumLogin User

API Authentication using Laravel SanctumGet Authenticated User

API Authentication using Laravel Sanctum

Thank you for reading this article.

It'd be a good idea to follow along with the simple demo app that can be found in this GitHub repo.

Read Also: Implement Passport In Laravel

 

Comments (0)

Comment


Note: All Input Fields are required.