Yii2 Rest API承载认证

Wou*_*den 9 authentication api rest yii2 bearer-token

我做了一个Yii2 REST API.使用API​​,您可以获得汽车列表.现在我想使用承载身份验证来保护API.但我不知道它是如何工作的.

首先.我在控制器的behavior方法中设置了authenticator.

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

这很好用.如果我转到URL,我将收到"未经授权"的消息.

在我的wordpress插件中,我已经创建了一个函数来使用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);
}
Run Code Online (Sandbox Code Playgroud)

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

我不知道该怎么做.

soj*_*oju 10

\yii\filters\auth\HttpBearerAuth::authenticate()只需致电\yii\web\User::loginByAccessToken():

$class = $this->identityClass;
$identity = $class::findIdentityByAccessToken($token, $type);
Run Code Online (Sandbox Code Playgroud)

所以你只需要findIdentityByAccessToken()在你的用户身份类中实现,例如:

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

  • 当`findIdentityByAccessToken`返回`null`认证时@WouterdenOuden将被拒绝.所以做你需要的任何逻辑(比如检查令牌有效性),如果认证失败则返回`null`或返回一个**用户**实例,`Yii :: $ app-> user-> identity`将保持如此您可以在应用程序内的任何位置使用它.检查[此](http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html)和[此](http://blog.neattutorials.com/angularjs-and-yii2-part- 2-authentication /)了解更多详情. (2认同)