【问题标题】:How can i get Basic authorization header and authenticate it for api by using php如何获取基本授权标头并使用 php 对 api 进行身份验证
【发布时间】:2017-01-30 12:58:43
【问题描述】:

如何获取基本授权标头并使用 PHP 对 API 进行身份验证。我创建了一个唯一的密钥,它被编码并存储在数据库中。我正在使用 Slim 框架 来获取其他 API。

我可以通过在 Slim 框架中使用 $request->headers(); 来获取标题。它返回所有指定的标头,但是如何使用我的数据库令牌检查该密钥。

有什么合适的方法吗?

【问题讨论】:

标签: php api header authorization slim


【解决方案1】:

我在 Slim Framework 3 中是这样做的:

我将中间件添加到所有请求中并检查了某个字符串的授权标头,如果未设置授权标头或与我的字符串不匹配,我只返回 400 HTTP 代码。

$app->add(function($request,$response,$next){
$authorization_header = $request->getHeader("Authorization");

if(empty($authorization_header) || ($authorization_header[0]!="test")){ //you can check the header for a certain string or you can check if what is in the Authorization header exists in your database

    return $response->withStatus(400);
}

$response = $next($request,$response);

return $response;

});

【讨论】:

  • 你应该使用苗条的响应而不是 header() 而是return $response->withStatus(400);
  • 是的,你是对的......谢谢..我要编辑答案
  • 这仅适用于 NGINX,因为 apache 拦截了授权标头,仅供参考
猜你喜欢
  • 2012-10-02
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多