garest / api-guard
A lightweight Laravel library for authenticating API clients without using user models
Installs: 10
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/garest/api-guard
Requires
- php: ^8.1
- laravel/framework: ^10.0|^11.0|^12.0
README
ApiGuard is a lightweight library for Laravel designed for secure API client authentication that does not require the creation or use of user models.
Features
- 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
Installation
composer require garest/api-guard
Publish config:
php artisan vendor:publish --tag=api-guard-config
Publish migrations:
php artisan vendor:publish --tag=api-guard-migrations
Run migrations:
php artisan migrate
Usage
Currently, ApiGuard only supports HMAC authentication. Full instructions on how to set up and use this method can be found by clicking here.
Error Rendering
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]); })
Failed Authentication Listener
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.