API Authentication using Laravel Sanctum

API Authentication using Laravel Sanctum

In this post we will give you information about API Authentication using Laravel Sanctum. Hear we will give you detail about API Authentication using Laravel Sanctum And how to use it also give you demo for it if it is necessary.

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 OAuth3 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>

Also see: 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="LaravelSanctumSanctumServiceProvider"

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 AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

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',
    IlluminateRoutingMiddlewareSubstituteBindings::class,
    LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::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 AppHttpControllersAuthController;

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

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

use IlluminateSupportFacadesHash;

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 LaravelSanctumNewAccessToken, 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 IlluminateSupportFacadesAuth;

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 IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

use AppHttpControllersAuthController;

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

Login User

Get Authenticated User

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.

Also see: Implement Passport In Laravel

 

Hope this code and post will helped you for implement API Authentication using Laravel Sanctum. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US