2

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;
            },
        ],
    ];
}
3
  • Try first following the Yii2 Authentication guide in yiiframework.com/doc/guide/2.0/en/rest-authentication. If you get stuck in some point please give some example codes you are working to get better help. Commented Jan 18, 2019 at 6:33
  • Yes, i followed it, and i am able to use both authentication in different API controllers, but in my case i have to user 2 auth methods in same controller. Commented Jan 18, 2019 at 7:42
  • Here i have used Basic auth method but for some actions in same API controller i want to use Composite Auth method Commented Jan 18, 2019 at 7:45

1 Answer 1

2

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'],
        ],
    ];
}
Sign up to request clarification or add additional context in comments.

4 Comments

According documentation (yiiframework.com/doc/guide/2.0/en/rest-authentication) this must be below the key authentificator. I updated this in your post
@Radon8472 I reverted your change, as code seems to be incorrect. Key does not matter for behaviors, only content of array is important, as it is configuration for behavior (and it is incorrect after your change).
Hmm okay, thats strange. I documentation says it should be unter the authentificator key
I changed key for CompositeAuth, it should be less confusing now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.