How to Use Laravel Sanctum for Api Token Authentication?

2 minutes read

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:

1
composer require laravel/sanctum

Next, publish the Sanctum configuration file using Artisan:

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

Finally, run the migrations to create the necessary tables:

1
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:

1
2
3
4
5
'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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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:

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

Related Resources

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!

Facebook Twitter LinkedIn Telegram Whatsapp

Related Posts:

To enable two-factor authentication on Coinbase, follow these steps:Log in to your Coinbase account.Go to the Security settings section.Click on the Enable two-factor authentication option.Choose the authentication method you prefer, such as using an authentic...
To pass data into an iframe in React.js, you can use the postMessage API. This API allows you to safely communicate between the parent window and the iframe. To send data from the parent window to the iframe, you can use the following code snippet: const ifram...
API (Application Programming Interface) in PHP is a way to connect different software systems or applications to interact and communicate with each other. It allows developers to access and use the functionality provided by another software or web service.With...