Ravi Gohil
Ravi Gohil

Reputation: 157

Yii2: how to use different auth methods in API

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

Answers (1)

rob006
rob006

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

Related Questions