Reputation: 157
I am working on API in Yii2, where I need to use different authentication methods for different actions.
How can I set CompositeAuth
for action1
, action2
and action3
, and HttpBasicAuth
for action4
and 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;
},
],
];
}
Upvotes: 2
Views: 841
Reputation: 22174
You can attach multiple auth behaviors and use only
property to specify list of actions which should be affected by each behavior:
public function behaviors() {
return [
'authentificator' => [
'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'],
],
];
}
Upvotes: 2