Yii2 Rest API 承载认证 [英] Yii2 Rest API Bearer Authentication

查看:23
本文介绍了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 并给我响应.我想在 de 数据库中搜索密钥,如果它存在,它还应该给我同一行中的 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() 只会调用 \yii\web\User::loginByAccessToken() :

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

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

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天全站免登陆