Key Secret Api Authentication extension for Laravel
composer require black-bits/key-secret-api-authenticationIn our case we want a project model, that has a key and a secret field, for api authentication. Therefore a user can have different projects, each with it's own key-secret pair for authentication. Instead of "extends Model", use "extends KeySecretAuthenticatableModel".
class Project extends KeySecretAuthenticatableModel
{
// ...
}Change the guard for api to the following...
'guards' => [
// ...
'api' => [
'driver' => 'key_secret',
'provider' => 'key_secret',
],
],... and add a new provider "key_secret" with reference to your Model
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'key_secret' => [
'driver' => 'eloquent',
'model' => App\Project::class,
],
],Change the MiddlewareGroup in the Kernel as you would for usage for api_token. Set the "auth" to "auth:api".
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
'auth:api',
'throttle:60,1',
'bindings',
],
];In "routes/api.php" create a route and start using it.
Route::get('test', function (Request $request) {
return "hello world - " . $request->user()->name;
});
// Be aware, that "$request->user()->name" will return the property "name" from our Project-Model and not from the referenced User-Model.Add a new Header to your API Call with a key "Authorization" and a value "Bearer xyz". xyz should be replaced with your base64_encoded key:secret pair.
$key = 'abc'
$secret = '12345'
$token = base64_encode($key . ':' . $secret);- The token should be refactored to use jwt.