black-bits/key-secret-api-authentication

Laravel 的 Key Secret Api Authentication 扩展

0.0.2 2017-10-12 00:55 UTC

This package is auto-updated.

Last update: 2024-08-29 04:25:40 UTC


README

Latest Version on Packagist Software License Build Status Total Downloads

Laravel 的 Key Secret Api Authentication 扩展

如何使用

1. 需求包

composer require black-bits/key-secret-api-authentication

2. 扩展你的模型(包含 key 和 secret 字段)

在我们的例子中,我们想要一个项目模型,它具有 key 和 secret 字段,用于 API 验证。因此,用户可以有多个不同的项目,每个项目都有自己的密钥-密钥对用于验证。而不是使用 "extends Model",请使用 "extends KeySecretAuthenticatableModel"。

class Project extends KeySecretAuthenticatableModel
{
    // ...
}

3. 配置 config/auth.php

将 API 的卫士更改为以下...

'guards' => [
    // ... 
    
    'api' => [
        'driver' => 'key_secret',
        'provider' => 'key_secret',
    ],
],

... 并添加一个新的提供者 "key_secret",并将其与您的模型相关联

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'key_secret' => [
        'driver' => 'eloquent',
        'model' => App\Project::class,
    ],
],

4. 修改 App\Http\Kernel.php 中的 MiddlewareGroup

根据 api_token 的用法更改 Kernel 中的 MiddlewareGroup。将 "auth" 设置为 "auth:api"。

protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        'auth:api',
        'throttle:60,1',
        'bindings',
    ],
];

5. 开始使用

在 "routes/api.php" 中创建一个路由并开始使用它。

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.

在您的 API 调用中添加一个新的 Header,键为 "Authorization",值为 "Bearer xyz"。xyz 应该被替换为您 base64 编码的 key:secret 对。

$key    = 'abc'
$secret = '12345'
$token  = base64_encode($key . ':' . $secret);

待办事项

  • 应重构令牌以使用 jwt。