Skip to content

A lightweight Laravel library for authenticating API clients without using user models

License

Notifications You must be signed in to change notification settings

mrgarest/api-guard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ApiGuard (API Authentication for Laravel)

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.

About

A lightweight Laravel library for authenticating API clients without using user models

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages