Laravel

Introduction to Laravel Sanctum: API Authentication

Laravel

Introduction to Laravel Sanctum: API Authentication

Laravel Sanctum is a lightweight package that provides a simple and secure way to handle API authentication in Laravel applications. It offers token-based authentication and is designed to work seamlessly with both SPA (Single Page Application) and mobile applications. In this post, we'll explore the basics of Laravel Sanctum and its implementation for API authentication, making your Laravel-powered APIs secure and user-friendly.

Installing Laravel Sanctum

To begin using Laravel Sanctum, you need to install it via Composer:

composer require laravel/sanctum

Next, run the migrations to create the necessary database tables:

php artisan migrate

Configuring Sanctum

After installing Sanctum, you need to configure it to work with your Laravel application. Open the config/auth.php file and update the guards and api driver settings:

'guards' => [
    // ...
    'api' => [
        'driver' => 'sanctum',
        'provider' => 'users',
    ],
],

'providers' => [
    // ...
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

Authenticating API Requests

With Sanctum configured, you can now authenticate API requests using tokens. To authenticate a user and obtain a token, create a login endpoint:

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

Route::post('/login', function (Request $request) {
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $token = $user->createToken('authToken')->plainTextToken;

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

    return response()->json(['message' => 'Unauthorized'], 401);
});

Protecting API Routes

To protect your API routes, you can use the auth:sanctum middleware. Apply this middleware to the routes that require authentication:

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

    // Other protected routes go here
});

Logging Out

To log out a user and invalidate their token, you can use the logout method:

Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
    $user = $request->user();
    $user->tokens()->delete();

    return response()->json(['message' => 'Logged out successfully'], 200);
});

Laravel Sanctum simplifies API authentication in Laravel applications, allowing you to create secure and reliable APIs with minimal effort. By implementing token-based authentication, you can protect your API routes and provide a seamless user experience for SPA and mobile applications.

With Laravel Sanctum's flexibility and straightforward configuration, you can focus on building powerful APIs while ensuring they remain secure and accessible only to authorized users.