ajax request call yii\web\User::loginRequired() to throw a ForbiddenHttpException
throw a UnauthorizedHttpException
let the client handle the non logged in interaction better
| Q | A
| ---------------- | ---
| Yii version | 2.0.14
| PHP version | 7.1.12
| Operating system | Centos 7.0
The exception is not raised if there is no Accept header or if the header contains text/html or application/xhtml+xml in it. This behavior could be altered via yii\web\User::$acceptableRedirectTypes and via $checkAcceptHeader argument in yii\web\User::loginRequired() calls.
> await fetch('/loginRequired', {headers: {Accept: 'text/html'}})
Response聽{url: "http://localhost/site/login", redirected: true, status: 200, statusText: "OK"}
> await fetch('/loginRequired', {headers: {Accept: 'application/json'}})
Response聽{redirected: false, status: 500, statusText: "Internal Server Error"}
I don't think, that Unauthorized exception is suitable here. RFC 7235 stands that Unauthorized status should be coupled with WWW-Authenticate header.
Most helpful comment
See https://github.com/yiisoft/yii2/pull/13829, https://github.com/yiisoft/yii2/issues/9846 and https://github.com/yiisoft/yii2/pull/7818.