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

问题描述 投票:0回答:1

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

如何为

CompositeAuth
action1
action2
设置
action3
,以及为
HttpBasicAuth
action4
设置
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;
            },
        ],
    ];
}
yii2 yii2-advanced-app
1个回答
2
投票

您可以附加多个身份验证行为并使用

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'],
        ],
    ];
}
© www.soinside.com 2019 - 2024. All rights reserved.