How to API Authentication in Laravel 11


API authentication in Laravel 11 can be handled in several ways, including token-based authentication (such as Laravel Passport or Laravel Sanctum), JWT (JSON Web Token), or custom authentication methods. Here's a guide on how to set up API authentication using Laravel Sanctum, which is a simple and lightweight option suitable for most applications.

Step-by-Step Guide for API Authentication Using Laravel Sanctum

1. Install Laravel Sanctum

First, install the Laravel Sanctum package via Composer:


composer require laravel/sanctum

2. Publish the Sanctum Configuration

Next, publish the Sanctum configuration file:


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

This will create a config/sanctum.php file.

3. Run the Sanctum Migrations

Sanctum comes with its own database migrations. Run them using the Artisan command:


php artisan migrate

4. Configure Sanctum Middleware

Add Sanctum's middleware to your api middleware group within your app/Http/Kernel.php file:


// app/Http/Kernel.php use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful; protected $middlewareGroups = [ 'web' => [ // other middleware ], 'api' => [ EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];

5. Add Sanctum's HasApiTokens Trait

Ensure that your User model uses the HasApiTokens trait provided by Sanctum:


// app/Models/User.php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // other model properties and methods }

6. Define Authentication Routes

Create authentication routes for login, registration, and other related actions in your routes/api.php file:


// routes/api.php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AuthController; 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::post('/logout', [AuthController::class, 'logout']); });

7. Create the AuthController

Create a new controller to handle the authentication logic:


php artisan make:controller AuthController

Open the generated AuthController.php file and implement the authentication methods:


// app/Http/Controllers/AuthController.php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; class AuthController extends Controller { public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8|confirmed', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); return response()->json(['message' => 'User registered successfully'], 201); } public function login(Request $request) { $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } $token = $user->createToken('auth_token')->plainTextToken; return response()->json(['access_token' => $token, 'token_type' => 'Bearer']); } public function user(Request $request) { return $request->user(); } public function logout(Request $request) { $request->user()->tokens()->delete(); return response()->json(['message' => 'Tokens revoked']); } }

8. Protecting Routes

To protect your routes, use the auth:sanctum middleware. Any route within this middleware group will require an authenticated user.


// routes/api.php Route::middleware('auth:sanctum')->group(function () { Route::get('/user', [AuthController::class, 'user']); Route::post('/logout', [AuthController::class, 'logout']); });

9. Testing Your API

You can now test your API endpoints using tools like Postman or cURL.

  • Register:


    POST /api/register { "name": "John Doe", "email": "john@example.com", "password": "password", "password_confirmation": "password" }
  • Login:


    POST /api/login { "email": "john@example.com", "password": "password" }
  • Get User Details:


    GET /api/user Authorization: Bearer {access_token}
  • Logout:


    POST /api/logout Authorization: Bearer {access_token}

Conclusion

By following these steps, you can set up API authentication in Laravel 11 using Laravel Sanctum. Sanctum provides a simple and lightweight approach to API token authentication, making it suitable for a wide range of applications. This setup includes registering and logging in users, protecting routes, and handling token management. 

Post a Comment

0 Comments