Skip to main content
WebForum

Back to all posts

How to Use Laravel Sanctum for Api Token Authentication?

Published on
2 min read
How to Use Laravel Sanctum for Api Token Authentication? image

In this guide, we’ll walk you through the process of using Laravel Sanctum for API token authentication, a lightweight package that simplifies API token and session cookie-based authentication for your Laravel applications. With Sanctum, you can easily secure your APIs without the complexity of OAuth2.

Laravel Sanctum

What is Laravel Sanctum?

Laravel Sanctum allows you to manage API tokens for users without the overhead of OAuth. It’s perfect for SPAs (Single Page Applications), mobile applications, and simple token-based APIs.

Prerequisites

Before starting, ensure you have the following:

  • Laravel installed in your project.
  • A basic understanding of Laravel development.

Installation

First, install Sanctum via Composer:

composer require laravel/sanctum

Next, publish the Sanctum configuration file using Artisan:

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

Finally, run the migrations to create the necessary tables:

php artisan migrate

Setting Up Sanctum

Configuring Middleware

To protect your API and ensure requests have valid tokens, add the Sanctum middleware to your api middleware group within your app/Http/Kernel.php file:

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

Authenticating Users and Issuing Tokens

You can issue tokens to users in your API routes. Here’s a simple example demonstrating how to do so within a controller method:

use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash;

public function login(Request $request) { $user = User::where('email', $request->email)->first();

if (!$user || !Hash::check($request->password, $user->password)) {
    return response()->json(\['message' => 'Invalid credentials'\], 401);
}

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

return response()->json(\['token' => $token\]);

}

Protecting Routes

To protect your routes, you can use the auth:sanctum middleware. This ensures that the incoming requests have valid tokens. Add it to any routes you need to secure:

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

Conclusion

Laravel Sanctum provides a simple and efficient way to manage API token authentication in your Laravel applications. With minimal configuration and powerful features, Sanctum is a great choice for developers looking to quickly set up secure API authentication.

Implement Sanctum today and enjoy a seamless and safe authentication experience in your Laravel projects!