Yii2 Rest API承载身份验证 [英] Yii2 Rest API Bearer Authentication

查看:140
本文介绍了Yii2 Rest API承载身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've made a Yii2 REST API. With the API you can get a list of cars. Now I want to use the Bearer Authentication to protect the API. But I don't know how it works.

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

First of all. I set up the authenticator in the behaviors method of my controller.

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

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

This works just fine. If I go to the URL I will get an 'Unauthorized' message.

在我的wordpress插件中,我做了一个使用API​​的函数,并设置了带有身份验证密钥的标头.

In my wordpress plugin I've made an function to use the API and set the header with the authentication key.

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并给我答复.我想在数据库中搜索密钥,如果它存在,还应该在同一行中给我ID或电子邮件.

But now my question is. How can I check in the API if this key is valid and give me the response. I want to search for the key in de database and if it exists it should also give me the id or email thats in the same row.

我不知道该怎么做.

推荐答案

\yii\filters\auth\HttpBearerAuth::authenticate() 将仅调用因此,您只需要实现 在您的用户身份类别中,例如:

So you just need to implement findIdentityByAccessToken() in your user identity class, e.g. :

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

这篇关于Yii2 Rest API承载身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆