API Authentication using Laravel Sanctum v11.x

Throughout the Laravel API authentication with Sanctum tutorial, you will learn API Authentication using Laravel Sanctum v11. Laravel Sanctum offers a streamlined authentication solution tailored for various applications including SPAs (Single Page Applications), mobile apps, and lightweight, token-based APIs.

In this step by step guide, we’ll demonstrate how to create RESTful API authentication system in Laravel utilizing the powerful features provided by the Laravel Sanctum package. You’ll gain a deeper understanding of API authentication in Laravel using Sanctum, enabling you to build scalable, secure, and efficient web and mobile applications.

Steps for Laravel API Authentications with Sanctum Example

  • Install Laravel 11 App
  • Configure Database Credentials
  • Create Api Controller
  • Configure Routes
  • Test Authentications apis using Postman

#1 Setup Laravel App

Before proceeding with the installation of Laravel 11, ensure that your system meets the following prerequisites:

  • Laravel 11 requires PHP version 8.2 or higher. You can verify your PHP version by running php -v in your terminal or command prompt. If you don’t have PHP 8.2 installed, you’ll need to upgrade your PHP version.
  • Laravel supports multiple database systems such as MySQL, PostgreSQL, SQLite, and SQL Server. In Laravel 11, they have predefined DB_CONNECTION=sqlite in the .env file, but if you are using MySQL, you will need to update it.

To install Laravel 11, run the following command in your terminal:

composer create-project --prefer-dist laravel/laravel:^11.0 laravel-sanctum-auth

If you prefer to install Laravel based on your PHP version, use the following command:

composer create-project --prefer-dist laravel/laravel laravel-sanctum-auth

#2 Database Credentials

In this step, you need to update your database credentials such as DB_CONNECTION, DB_DATABASE, DB_USERNAME and DB_PASSWORD in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=

#3 Installation and Setup Laravel Sanctum

Note: If you are using the Laravel 7 or below version then you can follow this step otherwise you can skip because above the Laravel 7-10 predefined the Laravel sanctum package for rest api authentication.

So, open the terminal and execute the below command to begin installing the Sanctum package into the Laravel app.

composer require laravel/sanctum

To add the sanctum provider you need to publish the sanctum configuration with the help of vendor publish.

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

Next, you need to register the sanctum middleware into the api array inside the Kernel.php file

protected $middlewareGroups = [
...
...
    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
...
...
];

Now you need to run the migrate command to generate default Laravel addition tables which are generated when you have installed the sanctum package.

php artisan migrate

In last, before we can start using Laravel Sanctum to create tokens for users, you need to update the User model using the HasApiTokens trait. So open the app/Models/User.php file and add the following modifications:

<?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 HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

#4 Create API Controller

Now, open the terminal and run the below command to create controller to make restful api authentication using Laravel Sanctum.

php artisan make:controller Api/AuthController

Now open the newly created file app\Http\Controllers\Api\AuthController.php and update Register, Login, User details code with Laravel sanctum for api authentication.

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class AuthController extends Controller
{
    public function register(Request $request)
    {

        $data = Validator::make($request->all(),[
            'name' => 'required',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|min:8',
        ]);

        if ($data->fails()) {
            return response()->json([
                'errors' => $data->errors()
            ], 422);
        }

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

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

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

    public function login(Request $request)
    {
        $data = Validator::make($request->all(),[
            'email' => 'required',
            'password' => 'required',
        ]);

        if ($data->fails()) {
            return response()->json([
                'errors' => $data->errors()
            ], 422);
        }

        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('auth_token')->plainTextToken;

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

    public function user(Request $request)
    {
        return $request->user();
    }
}

#5 Create REST API Auth Routes

Now it’s time to update the routes for api authentication using Laravel Sanctum.

So open the routes/api.php file to create the register, login and get log-in user details routes.

<?php

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

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

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

// Route::middleware('auth:sanctum')->group( function () {
//     Route::get('/user', [AuthController::class, 'user']);
// });

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

Learn Also: Laravel Vuejs Authentication using Sanctum

#6 Test Laravel Sanctum REST API’s using Postman

We have successfully created the Laravel authentication using Sanctum. So we will run the php artisan command to test our api’s.

php artisan serve

Create New User

To create a new user you need to set a POST request with your API url http://127.0.0.1:8000/api/register and add the name, email, password and password_confirmation.

Login User

For login api you need to make a POST request to http://127.0.0.1:8001/api/ login with your email and password.

Get Login User

If we try to access the /user endpoint with a valid token, which will return our logged-in user details.

#7 Conclusion

Finally, the Laravel Sanctum API authentication example is ended, hope you will like it. Laravel Sanctum is easy to install and configure, also we can generate a multi-token, with the specific role given to every token.