Build a SPA Authentication using Laravel Sanctum

Hi artisan, in this tutorial i am going to discuss about api authentication and the process will be using sanctum. Codecheef already did many types api authenticantion example like using laravel passport, jwt api auth etc. But in this example i am going to use laravel sanctum.

In this laravel sanctum api authentication example i will simply create a authentication system with logout system. In Laravel sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API.

Sanctum does not use tokens of any kind. Instead, Laravel sanctum uses Laravel's built-in cookie based session authentication services. Laravel sanctum is a good option for spa authentication. So let's start laravel sanctum spa authentication example. 

 

Step 1 : Install Laravel

In the first step, we require to get fresh Laravel application using to make our laravel sanctum spa authentication, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel ApiAuth

 

Step 2: Install Sanctum

We can install Laravel Sanctum via the Composer package manager:

composer require laravel/sanctum

 

Then run the config file

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

 

php artisan migrate

 

Next, if you plan to utilize Sanctum to authenticate an SPA, you should add Sanctum's middleware to your api middleware group within your application's app/Http/Kernel.php

app/Http/Kernel.php

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

 

Recommended : Laravel 8.x Passport API Authentication Tutorial Example

 

Step 3: Configure User Model

In our model which we are going to use for sanctum that has to be configured like below. Add HasApiTokens class of Sanctum and In auth.php, we added api auth configuration.

app/Models/User.php

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;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

 

Step 4: Create API Routes

In this step, we need to create api routes. Laravel provide api.php file for writeing web api route. So, let's create those below route on that file.

routes/api.php

use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

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

// Protected routes
Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});

 

Read also : Laravel 8.x JWT (Json Web Token) Authentication Example

 

Step 5: Create Controller

Time to write our authetication code in our controller. So create controller and paste those below code in that controller

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    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'])
        ]);

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

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response, 201);
    }

    public function login(Request $request) {
        $fields = $request->validate([
            'email' => 'required|string',
            'password' => 'required|string'
        ]);

        // Check email
        $user = User::where('email', $fields['email'])->first();

        // Check password
        if(!$user || !Hash::check($fields['password'], $user->password)) {
            return response([
                'message' => 'Bad creds'
            ], 401);
        }

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

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response, 201);
    }

    public function logout(Request $request) {
        auth()->user()->tokens()->delete();

        return [
            'message' => 'Logged out'
        ];
    }
}

 

All are set to go. Now start your server and open your postman to test our sanctum authentication api.

 

Register Api
API: http://127.0.0.1:8000/api/register
REQUEST: POST

 

laravel-sanctum-api-authentication-example


 

Login Api
API: http://127.0.0.1:8000/api/login
REQUEST: POST

 

sanctum-api-authentication-example

 

Before testing the logout api make sure in details api we will use following headers as listed bellow:

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,

]

 

Logout Api
API: http://127.0.0.1:8000/api/logout
REQUEST: POST
HEADER: Bearer Token

 

laravel-sanctum-login-registration-example

 

Recommended : Laravel Sanctum Authentication Example with Product Api

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.