Overview

Hope you have understood that How to implement REST APIs in Laravel, Now you need to make your apis secure to access. To authenticate your Laravel API, we’ll use Laravel Sanctum, which is lightweight and perfect for token-based authentication in REST APIs. Here’s how to implement it.


1. Install Laravel Sanctum

Run the following command to install Sanctum:

composer require laravel/sanctum

Then, publish the configuration file and run migrations:

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

2. Configure Sanctum in Laravel

Modify User.php Model

Open app/Models/User.php and add HasApiTokens:

use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
    use HasApiTokens, HasFactory, Notifiable; 
}

3. Register Sanctum Middleware

In app/Http/Kernel.php, add the Sanctum middleware under api:

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

4. Create Authentication Controller

php artisan make:controller AuthController

Modify app/Http/Controllers/AuthController.php:

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

class AuthController extends Controller {

    // Register a new user
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

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

        $token = $user->createToken('API Token')->plainTextToken;
        
        return response()->json(['user' => $user, 'token' => $token], 201);
    }


    // Login user
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        $user = Auth::user();
        $token = $user->createToken('API Token')->plainTextToken;
        
        return response()->json(['user' => $user, 'token' => $token], 200);
    }

    // Logout user
    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'Logged out successfully'], 200);
    } 
}

5. Define API Routes

Modify routes/api.php:

use App\Http\Controllers\AuthController;
use App\Http\Controllers\PropertyController;
use Illuminate\Support\Facades\Route;

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

// Protected routes (require authentication)
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::apiResource('properties', PropertyController::class);
});

6. Test Authentication API

Start the server:

php artisan serve

Register a User

curl -X POST http://127.0.0.1:8000/api/register \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com", "password": "password", "password_confirmation": "password"}'

Login User

curl -X POST http://127.0.0.1:8000/api/login \
-H "Content-Type: application/json" \
-d '{"email": "john@example.com", "password": "password"}'

Response:

{
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    },

    "token": "3|A1b2C3d4E5..." 
}

Copy the token for the next steps.

Access Protected Routes

Use the token in the Authorization header:

curl -X GET http://127.0.0.1:8000/api/properties \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Logout

curl -X POST http://127.0.0.1:8000/api/logout \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

7. Next Steps

  • Implement role-based access control (RBAC)
  • Secure API using CORS and rate limiting
  • Connect frontend (React, Vue, etc.) to this API