ApiGuard is a lightweight library for Laravel designed for secure API client authentication that does not require the creation or use of user models.
- HMAC request signing (SHA-256)
- Protection against replay attacks (timestamp + nonce)
- Client-based authentication (no users)
- Scope-based authorization
- Caching for performance
- Logging failed authentication attempts
composer require garest/api-guardPublish config:
php artisan vendor:publish --tag=api-guard-configPublish migrations:
php artisan vendor:publish --tag=api-guard-migrationsRun migrations:
php artisan migrateCurrently, ApiGuard only supports HMAC authentication. Full instructions on how to set up and use this method can be found by clicking here.
To correctly handle and display errors when calling the API, you need to configure custom rendering of ApiGuardException exceptions.
In Laravel 12, this is done in bootstrap/app.php:
use Garest\ApiGuard\Exceptions\ApiGuardException;
withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (ApiGuardException $e) {
return response()->json([
'status' => $e->status(),
'code' => $e->code(),
'message' => $e->getMessage(),
], $e->status());
});
// Disables error logging
$exceptions->dontReport([ApiGuardException::class]);
})You can hook into failed API authentication attempts via a Laravel event listener:
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Garest\ApiGuard\Events\AuthFailed;
Event::listen(AuthFailed::class, function ($event) {
// Access failed request and exception
$request = $event->request;
$exception = $event->exception;
// Example: log failure
Log::warning('Authentication failed', [
'ip' => $request->ip(),
'path' => $request->path(),
'method' => $request->method(),
'message' => $exception->getMessage(),
]);
});This allows you to track, log, or notify whenever a client fails authentication.