我正在使用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;
},
],
];
}
答案 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'],
],
];
}