Authentication with Laravel (with Sanctum)

Tips on how to manage authentication with Laravel Sanctum.

June 27, 2024 Code

Given the structure and excerpts from your Laravel application, it seems you're already leveraging Laravel's built-in authentication mechanisms, which is a good start. However, to enhance security, especially for a headless backend serving a frontend application, consider the following recommendations:

1. Use Laravel Sanctum for API Token Authentication

Laravel Sanctum provides a simple package for API token authentication, which is ideal for SPAs (Single Page Applications), mobile applications, and simple token-based API services. Sanctum allows each user to generate multiple API tokens for their account, which can be used to authenticate API requests.

Installation:

composer require laravel/sanctum

Migration:

Publish the Sanctum configuration file and run the migrations to create the necessary tables.

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

php artisan migrate

Configuration:

Ensure your sanctum configuration is set correctly in config/sanctum.php. You've already got a snippet in your workspace, so make sure the expiration and middleware settings are to your liking.

Usage:

To protect routes, use the auth:sanctum middleware. For example, in your routes/api.php:

<?php

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

return $request->user();

});

2. Ensure Strong Password Policies

You're already using Rules\Password::defaults() in your NewPasswordController. Consider customizing the password rules to enforce stronger policies. For example:

<?php

'password' => ['required', 'confirmed', Rules\Password::min(12)->mixedCase()->numbers()->symbols()],

3. Rate Limiting

Laravel provides easy ways to implement rate limiting. This can help protect against brute-force attacks. You've already got some rate limiting in place ('throttle:6,1'), but consider applying it more broadly or adjusting the limits based on your application's needs.

4. HTTPS Everywhere

Ensure all communications between your frontend, backend, and any external services are over HTTPS. This prevents man-in-the-middle attacks and ensures data integrity and confidentiality.

5. Regularly Update Dependencies

Keep your Laravel application and its dependencies up to date. Regular updates can ensure you have the latest security patches.

6. CSRF Protection

Laravel automatically generates and verifies CSRF tokens for POST, PUT, PATCH, and DELETE requests. Ensure that your frontend application is correctly handling CSRF tokens when making such requests.

7. Validate and Sanitize Input

Always validate and sanitize user inputs to prevent SQL injection, XSS (Cross-Site Scripting), and other common web vulnerabilities. Laravel provides a robust validation system that you should leverage.

Code Snippet for API Token Generation:

Here's how you might generate and return a new API token upon user login, assuming you're using Sanctum:

<?php

use Illuminate\Http\Request;

use App\Models\User;

use Illuminate\Support\Facades\Hash;

Route::post('/login', function (Request $request) {

$request->validate([

'email' => 'required|email',

'password' => 'required',

]);

$user = User::where('email', $request->email)->first();

if (!$user || !Hash::check($request->password, $user->password)) {

return response()->json(['message' => 'The provided credentials are incorrect.'], 401);

}

return $user->createToken('token-name')->plainTextToken;

});

Invely's