API Authentication with Sanctum in Laravel 12 | Secure Your Laravel APIs
This blog provides a detailed guide on setting up API authentication using Sanctum in Laravel 12.
Introduction
In modern web applications, APIs are essential for connecting mobile apps and frontend frameworks with the backend. **Sanctum** provides an easy and lightweight way to handle API authentication in Laravel 12. In this blog, we’ll walk through how to set up API authentication using Sanctum in Laravel 12.
Step 1: Install Sanctum
To get started with **Sanctum**, you need to install it using **Composer**:
composer require laravel/sanctum
Once installed, you will need to publish Sanctum’s configuration file:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This command will create a **sanctum.php** configuration file in the **config** directory.
Step 2: Run Sanctum Migrations
Sanctum requires a database table to store API tokens. Run the following migration command to set up the necessary database tables:
php artisan migrate
Step 3: Set Up Sanctum Middleware
To ensure your API routes can authenticate users, you’ll need to add Sanctum’s middleware to the **`bootstrap/app.php`** file:
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
Then, in the **`middlewareGroups`** array, add **`EnsureFrontendRequestsAreStateful`** for API routes:
protected $middlewareGroups = [
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
EnsureFrontendRequestsAreStateful::class,
],
];
Step 4: Define API Routes
Once the setup is complete, you can define protected routes in **`routes/api.php`**:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
This route will now require a valid API token for access.
Step 5: Authenticating Users via Tokens
Now let’s see how we can authenticate users via API tokens. First, you need to create a **LoginController** to handle user authentication:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('YourAppName')->plainTextToken;
return response()->json(['token' => $token]);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
}
This controller attempts to log in the user and, if successful, returns a generated token.
Conclusion
In this blog, we have walked through the process of setting up **API authentication with Sanctum** in **Laravel 12**. Sanctum provides a simple and secure way to authenticate API users with tokens, making it ideal for SPA and mobile apps. By following these steps, you can easily implement token-based authentication in your Laravel APIs.