Laravel Sanctum

Last Updated: February 4, 2022

Laravel Sanctum provides a lightweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs

If you build single page application with Vue, React, or Angular then you can use the Sanctum for REST API validation.

You can do the API authentication with a few lines of code.

You can use Sanctum to authenticate SaaS applications ( Multi-tenant applications) by adding some additional code.

Each user of the application can generate multiple tokens

Tokes can consist of abilities that can perform so you can use this for access control management

You can generate API tokens without using complicated OAuth. This API token is stored in the database table and incoming HTTP requests against this API token.

Installation

(1) First install the sanctum using composer

composer require laravel/sanctum

(2) Publish configuration and migration files

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

(3) Run the database migration

php artisan migrate

(4)  if you plan to utilize Sanctum to authenticate a SPA, you should add Sanctum’s middleware to your API middleware group within your application’s app/Http/Kernel.php file:

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

How to register a new user

App\Http\Controllers\UserController.php

 public function register(Request $request)
    {

        $fields = $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|unique:users,email',
            'password' => 'required|string|confirmed',
        ]);
        $user = User::create([
                'name' => $fields['name'],
                'email' => $fields['email'],
                'password' => bcrypt($fields['password']),
            ]
        );

        return response()->json(['token' => $user->createToken('tokens')->plainTextToken], 200);
    }

routes\api.php

Route::post('/user/register', 'App\Http\Controllers\UserController@register');



Testing the code with Postman

How to login

App\Http\Controllers\UseController.php

 public function login(Request $request)
 {

        $fields = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);

        $user = User::where('email',$request->email)->first();

        if(!$user || !Hash::check($request->password,$user->password) ){
            return response()->json(['type'=>'login_failed','message' => 'invalid_credentials'], 200);
        }

        return response()->json(['token' => $user->createToken('tokens')->plainTextToken], 200);
}

routes/api.php

Route::post('/user/login', 'App\Http\Controllers\UserController@login');

How to logout

App\Http\Controllers\UseController.php

public function logout(Request $request)
{
       if (Auth::check()) {
            Auth::user()->tokens->each(function ($token, $key) {
                $token->delete();
            });
            return response()->json("Token Deleted");
        } else {
            return response()->json("No Authenticated User ");
        }
 }

routes/api.php

To protect the route, middleware named auth:sanctum is added

Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('/user/logout', 'App\Http\Controllers\UserController@logout');
});
Test