haustech / api-key-auth
API key authentication
1.0.2
2023-02-19 09:55 UTC
Requires (Dev)
- orchestra/testbench: ^7.0
- phpunit/phpunit: ^9.6
This package is not auto-updated.
Last update: 2025-07-07 19:29:22 UTC
README
About
This package contains a solution for a simple API authentication using API keys:
- A middleware that validates a request token in the incoming request. The request header
token
needs to contain a valid API key. - An API key generator as a Artisan command.
- Generated keys are stored in the database table "api_keys".
- The ability to restrict access based on IP.
Installation
composer require haustech/api-key-auth
Generate an API key
Syntax:
php artisan generate:apikey <application name> <allowed ip address>(optional)
The command generates an API key for the specified application, stores it in the database and outputs it in the terminal. The application name is just to keep track of the keys, there is no logic that validates it in any way.
Example:
php artisan generate:apikey SomeApplication 666.666.666.666
Generates a key for SomeApplication
and requires the IP of that application to be 666.666.666.666
.
If the second argument is left blank, the API key can be used from any IP.
Using the middleware
// api.php
Route::get('/my-route', [MyController::class, 'show'])->middleware('api_key');
Querying API keys
$all = ApiKey::all();
$byIpRestriction = ApiKey::where('ip', '1.2.3.4')->get();
$byApplication = ApiKey::where('application', 'SomeApplication')->get();