Yii2中的自定义身份验证问题


Custom authentication issue in Yii2

我为Yii2 RESTful项目添加了一个自定义身份验证组件,它正在验证凭据,但它没有将有效的User对象返回给''Yii::$app->User

组件如下所示:

public function authenticate($user, $request, $response) {
    $bearerToken = 'Yii::$app->getRequest()->getQueryParam('bearer_token');
    $user = Account::findIdentityByAccessToken($bearerToken);
    return $user;
}

账户模型方法如下:

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

我可以看到$user是在authenticate()方法中调试时Account的预期记录,但''Yii::app()->user似乎是一个新加入的用户。''Yii::app()->user->identity等于null。

有人看到我在这里做错了什么吗?

要登录用户,这还不够:

Account::findIdentityByAccessToken($bearerToken);

您需要在authentificate()内部调用$user->login($identity)。例如,请参阅它是如何在yii''web''User loginByAccessToken():中实现的

public function loginByAccessToken($token, $type = null)
{
    /* @var $class IdentityInterface */
    $class = $this->identityClass;
    $identity = $class::findIdentityByAccessToken($token, $type);
    if ($identity && $this->login($identity)) {
        return $identity;
    } else {
        return null;
    }
}

因此,您也可以在自定义身份验证方法中调用它:

$identity = $user->loginByAccessToken($accessToken, get_class($this));

例如,请参阅如何在yii''filters''auth''QueryParamAuth中实现它。

您还需要返回$identity,而不是$user。此外,代码中缺少处理失败的功能。看看它是如何在内置的身份验证方法中实现的:

  • HttpBasicAuth
  • HttpBearerAuth
  • QueryParamAuth

更多来自官方文档:

  • yii''web''用户登录()
  • yii''filters''auth''AuthInterface

更新:

没有什么强迫你使用loginByAccessToken(),我只是举了一个例子。

下面是我不久前写的一个自定义身份验证方法的例子,不确定它是否100%安全和真实,但我希望它能帮助你理解这些细节:

自定义身份验证方法:

<?php
namespace api'components;
use yii'filters'auth'AuthMethod;
class HttpPostAuth extends AuthMethod
{
    /**
     * @see yii'filters'auth'HttpBasicAuth
     */
    public $auth;
    /**
     * @inheritdoc
     */
    public function authenticate($user, $request, $response)
    {
        $username = $request->post('username');
        $password = $request->post('password');
        if ($username !== null && $password !== null) {
            $identity = call_user_func($this->auth, $username, $password);
            if ($identity !== null) {
                $user->switchIdentity($identity);
            } else {
                $this->handleFailure($response);
            }
            return $identity;
        }
        return null;
    }
}

REST控制器中的用法:

/**
 * @inheritdoc
 */
public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpPostAuth::className(),
        'auth' => function ($username, $password) {
            $user = new User;
            $user->domain_name = $username;
            // This will validate password according with LDAP
            if (!$user->validatePassword($password)) {
                return null;
            }
            return User::find()->username($username)->one();
        },
    ];
    return $behaviors;
}

指定$auth可调用也可以在HttpBasicAuth中找到。