【问题标题】:Laravel 8 - How to implement simple API key authenticationLaravel 8 - 如何实现简单的 API 密钥认证
【发布时间】:2021-12-18 01:29:27
【问题描述】:

我正在尝试在 Laravel 8 中为我的 API 实现一个非常简单的原型(非生产)身份验证系统。我的目标是让任何拥有硬编码 API 密钥的用户都能够使用端点。否则,他们将在所有端点收到 401 错误。用户必须将 API 密钥作为 URI 参数包含在内,格式如下例所示:

'hostAddress'/api/endpoint1?apikey='APIkey'

其中“hostAddress”代表主机 ipv6 地址,“APIkey”代表硬编码的 API 密钥。

我为这个问题所做的每一次搜索都会让我找到 Laravel 8 文档 (https://laravel.com/docs/8.x/authentication)。但是,文档中的身份验证解决方案比我要查找的要复杂得多。

如何在不使用复杂的 Laravel 包(如 Passport 和 Sanctum)的情况下实现这个简单的身份验证系统?

【问题讨论】:

  • 我错过了什么吗?只需检查该参数是否已提供并且它是否符合您的预期。
  • 我会查看Manually Authenticating Users 部分
  • 我猜你可以检查middleware 中的url 参数。即:if ($request->query('APIkey') !== 'my-secret-key') { return return response(['not allowed'], 403); },当然,将中间件应用于所有路由
  • 在您的概念验证走得太远之前,如果可能的话,我强烈建议您将密钥绑定到单个用户。如果您有一个全局共享 API 密钥,那么“用户”的概念就不存在了,或者,您最多只有一个用户。

标签: php laravel authentication laravel-8 api-key


【解决方案1】:

只需使用middleware。在 config/app.php 中添加您的密钥

[
  'api_key' => env('API_KEY'),
]

创建中间件并将其添加到 App\Http\Kernel

namespace App\Http\Middleware;
class ApiKeyMiddleware
{
  public function handle($request, Closure $next)
  {
    if(!$key = $request->get('apikey') or $key !== config('app.api_key'){
      throw new AuthenticationException('Wrong api key');
    }
  }
}
class Kernel extends HttpKernel
{
  protected $middlewareGroups = [
        'api' => [
            App\Http\Middleware\ApiKeyMiddleware::class
            'throttle:300,1',
            'bindings',
        ],
  ]
}

【讨论】:

    猜你喜欢
    • 2022-12-24
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2022-01-13
    • 2018-07-01
    • 2012-12-18
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多