如何获取基本授权标头并使用 PHP 对其进行 API 身份验证

问题描述 投票:0回答:1

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

我可以通过在 Slim Framework 中使用

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

有什么正确的方法可以做到这一点吗?

php http-headers authorization slim
1个回答
0
投票

我在 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;

});
© www.soinside.com 2019 - 2024. All rights reserved.