Yii2:如何在API中使用不同的身份验证方法

时间:2019-01-18 05:05:17

标签: yii2 yii2-advanced-app

我正在使用Yii2中的API,在这里我需要对不同的操作使用不同的身份验证方法。

如何为CompositeAuthaction1action2设置action3,为HttpBasicAuthaction4设置action5

public function behaviors()
{
    return [
        'basicAuth' => [
            'class' => \yii\filters\auth\HttpBasicAuth::className(),
            'auth' => function ($username, $password) {
                $user = User::find()->where(['username' => $username])->one();
                if ($user->verifyPassword($password)) {
                    return $user;
                }
                return null;
            },
        ],
    ];
}

1 个答案:

答案 0 :(得分:1)

您可以附加多个身份验证行为,并使用only属性来指定应受每种行为影响的操作列表:

public function behaviors() {
    return [
        'compositeAuth' => [
            'class' => \yii\filters\auth\CompositeAuth::className(),
            'authMethods' => [/* ... */],
            'only' => ['action1', 'action2', 'action3'],
        ],
        'basicAuth' => [
            'class' => \yii\filters\auth\HttpBasicAuth::className(),
            'auth' => function ($username, $password) {
                $user = User::find()->where(['username' => $username])->one();
                if ($user->verifyPassword($password)) {
                    return $user;
                }
                return null;
            },
            'only' => ['action4', 'action5'],
        ],
    ];
}