问题描述
我有一个使用 API 令牌身份验证的 Laravel 应用程序。默认情况下,用户需要将 api_token
参数作为 URL 的一部分传递,但我想将 api_token
更改为自定义名称参数,如 api_key
。
目前完整的 URL 如下所示:
https://www.example.com/api/v2/?api_token=something&action=balance
但是我希望它看起来像下面这样:
https://www.example.com/api/v2?api_key=something&action=balance
或
https://www.example.com/api/v2?key=something&action=balance
我的 API 路由使用了一个名为 auth:api
的中间件,但我无法找到该中间件来尝试更改其配置。
解决方法
我已经有一段时间没有这样做了,但我相信 auth.guards.api.input_key
设置将允许您指定它。所以你的 auth.php
部分看起来像这样:
<?php
return [
"guards" => [
"api" => [
"driver" => "token","provider" => "users",// the database table
"storage_key" => "api_token",// the database column
"input_key" => "api_key",// the query string component
"hash" => true,],];
,
您可以简单地创建自己的中间件
public function handle($request,Closure $next)
{
$token = request('key'); //it can be anything
if ($token != 'abc') { // this value can be static or can be get from database
return response([
'error' => 2,'message' => ["Access Denied"]
]);
}
return $next($request);
}
在这里你可以匹配令牌并允许他们某些请求
注意:它适用于 url 参数而不是 headers 令牌,您需要从 header 中获取令牌