Yii2 Rest API 承载认证

Yii2 Rest API Bearer Authentication

我做了一个 Yii2 REST API。使用 API 您可以获得汽车列表。现在我想使用 Bearer Authentication 来保护 API。但是我不知道它是如何工作的。

首先。我在控制器的行为方法中设置了身份验证器。

public function behaviors(){
    return [
        'contentNegotiator' => [
            'class' => ContentNegotiator::className(),
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ],
        'authenticator' => [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBearerAuth::className(),
            ],
        ]
    ];
}

这很好用。如果我去 URL 我会收到 'Unauthorized' 消息。

在我的 wordpress 插件中,我创建了一个函数来使用 API 并使用身份验证密钥设置 header。

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);
}

但现在我的问题是。如果此密钥有效,我如何检查 API 并给我回复。我想在 de 数据库中搜索密钥,如果它存在,它还应该给我同一行中的 ID 或电子邮件。

我不知道该怎么做。

\yii\filters\auth\HttpBearerAuth::authenticate() will simply call \yii\web\User::loginByAccessToken() :

$class = $this->identityClass;
$identity = $class::findIdentityByAccessToken($token, $type);

因此您只需要在您的用户身份 class 中实现 findIdentityByAccessToken(),例如:

public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne(['auth_key' => $token]);
}