yii2: Rest API basic authentication always returns 401
What steps will reproduce the problem?
Making api call with basic auth. Call compositeAuth in Module:
public function behaviors() {
return [
....
[
'class' => CompositeAuth::className(),
'except' => [
.....
],
'authMethods' => [
[
'class' => HttpBasicAuth::className(),
'auth' => function ($username, $password) {
// do something
},
],
[
'class' => MyCustomizedAuth::className(),
],
],
],
];
}
What is the expected result?
It will authenticate with the right credential - supplied as basic auth in header.
What do you get instead?
Returns 401 with message “Your request was made with invalid credentials.”
Additional info
Q | A |
---|---|
Yii version | 2.0.46 |
PHP version | 8.1.9 |
Operating system | Ubuntu 20.04 |
After some digging, it’s caused by this fix - https://github.com/yiisoft/yii2/commit/f72310c398759841a0f8b52e1aba7990086c0d9c
Commenting out the if condition added in this fix, it’s authenticated correctly.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 15 (7 by maintainers)
Commits related to this issue
- Fix #19517: Fix regression in `CompositeAuth::authenticate()` introduced in #19418 — committed to sam6666525/yii2 by WinterSilence 2 years ago
- Fix #19517: Fix regression in `CompositeAuth::authenticate()` introduced in #19418 — committed to maxodrom/yii2 by WinterSilence 2 years ago
The issue I’m having is not to do with except and only config. The issue is trying to do basic auth but the authentication function wasn’t called because of the if statement added by this fix: https://github.com/yiisoft/yii2/blame/f72310c398759841a0f8b52e1aba7990086c0d9c/framework/filters/auth/CompositeAuth.php#L73
The if statement doesn’t meet ($this->owner is null), the authenticate function doesn’t get called, hence the authentication always fails. If line 73 and 78 commented out, it gets authenticated.
Downgrade to Yii V2.0.45 and it works.
@AleMercadal also, you can do it via config(
$config['container']['definitions']
)Right way is create your base web controller extends by module controllers: