【问题标题】:Yii2 Rest API Bearer AuthenticationYii2 Rest API 承载认证
【发布时间】:2016-06-13 17:20:43
【问题描述】:

我制作了一个 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,我会收到一条“未经授权”的消息。

在我的 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);
}

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

我不知道该怎么做。

【问题讨论】:

  • 那么每个客户都应该有自己的accesstoken?你想使用 oauth2 吗?

标签: api rest authentication yii2 bearer-token


【解决方案1】:

\yii\filters\auth\HttpBearerAuth::authenticate() 将简单地调用\yii\web\User::loginByAccessToken()

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

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

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

【讨论】:

  • 在课堂上,我使用了另一个表,而不是 access_tokens 所在的位置。知道如何检查另一个表中的访问令牌吗?
  • @WouterdenOuden 当findIdentityByAccessToken 返回null 时,身份验证将被拒绝。因此,请在其中执行您需要的任何逻辑(例如检查令牌有效性)并在身份验证失败时返回 null 或返回 Yii::$app->user->identity 将持有的 user 实例,以便您可以在内部的任何地方使用它你的应用程序。查看thisthis 了解更多详情。
  • ...您可能还需要构建操作来处理登录、注册等...就像在example 中一样。
  • 所以我可以用 one() 进行查询,如果找不到任何内容,它将返回 null?如果它找到数据,则身份验证会成功?
  • 完全正确。请记住 findIdentityByAccessToken 应该返回 nulluser 实例。 (请注意,默认情况下,findOne() 将在未找到用户时返回 null
猜你喜欢
  • 2015-10-18
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多