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