由于某种原因,我的Yii2 REST API身份验证不再起作用。
我写了一个函数来从我的API获得响应:
function getJSON($template_url) {
$authorization = "Authorization: Bearer " . get_option("auth_key");
// Create curl resource
$ch = curl_init();
// Set URL
curl_setopt($ch, CURLOPT_URL, $template_url);
// Return transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
// $output contains output as a string
$output = curl_exec($ch);
// Close curl resource
curl_close($ch);
return json_decode($output, true);
}
这给了我以下回应:
数组([name] =>未经授权[message] =>您正在申请无效凭据。[code] => 0 [status] => 401 [type] => yii \ web \ UnauthorizedHttpException)
我的控制器里有这个:
public function behaviors(){
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
'authenticator' => [
'class' => CompositeAuth::className(),
'except' => ['activate'],
'authMethods' => [
HttpBearerAuth::className(),
],
]
];
}
这是User类中的findIdentityByAccessToken:
public static function findIdentityByAccessToken($token, $type = null) {
$query = (new Query())
->select([
'kl.access_token access_token',
])
->from('klanten kl')
->where(['kl.access_token' => $token])
->one();
return $query;
}
数据库表有一列access_token。我已经检查过我在getJSON函数中使用的访问令牌是否在数据库中可用,并且它是。所以我不知道我做错了什么。
答案 0 :(得分:0)
这也可能是不同Apache系统上的请求标头的问题。有时授权标题会丢失。将以下代码添加到您的htaccess:
$