Laravel 9 REST API Authentication Example using Sanctum

Hello Artisan,

In this tutorial, I will show you how to create api authentication in your Laravel 9 application using sanctum. You know that Laravel Sanctum provides a cool authentication system for single-page applications, mobile applications, and simple, token-based APIs. Laravel Sanctum allows each user of our application to generate multiple API tokens for their account

Laravel sanctum can be a good option to create single page api authentication i think. For this reason, I will show you how to work with laravel 9 sanctum API authentication example. From this Laravel 9 sanctum tutorial, you will learn laravel 9 rest API auth system using sanctum. After completing this tutorial, we can see laravel 9 sanctum spa API example.

 

Step 1 : Install Laravel  9

In the first step, we require to get a fresh Laravel 9 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. So fun below command to install it:

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 a 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 9 Custom Token Based Api Authentication Tutorial

 

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 provides an api.php file for writing the web API route. So, let's create those below routes 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 authentication code in our controller. To create a controller and paste those below code in that controller

app/Http/Controllers/AuthController.php

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, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js