基本REST API身份验证错误


Yii2 basic REST API authentication error

由于某些原因,我的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);
}

这给了我以下的响应:

Array ([name] => Unauthorized [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(),
            ],
        ]
    ];
}

这是用户类中的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函数中使用的访问令牌是否在数据库中可用。所以我不知道我做错了什么

这也可能是不同Apache系统上的请求头的问题。有时,授权头会丢失。在你的htaccess中添加下面的代码:

 SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

GitHub上缺少授权头讨论