【发布时间】:2022-01-22 09:03:25
【问题描述】:
我在 cakephp 4 中使用插件 Authentication 2。
当用户未登录时以及在 ajax 请求的情况下,我想抛出一个 UnauthenticatedException。
目标是在 JSON 中捕获异常。
这是我的服务器代码:
// in src/Controller/Admin/AdminController.php
use Authentication\Authenticator\UnauthenticatedException;
class AdminController extends AppController {
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Authentication.Authentication');
}
public function beforeFilter(EventInterface $event)
{
parent::beforeFilter($event);
// The server receives an ajax request and the user is not logged in (any more), an UnauthenticatedException is thrown
if ($this->request->is('ajax') && $this->request->getAttribute('identity') === null) {
throw new UnauthenticatedException('Please log in');
}
}
}
这是我来自客户端的代码:
$.ajax({
dataType: 'json';
type: 'POST',
data: $(form).serialize(),
// [...]
})
// [...]
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseJSON); // There's no responseJSON in jqXHR...
alert("(" + errorThrown + ")" + jqXHR.responseJSON.message);
if (errorThrown == 'Unauthenticated') {
location.reload();
}
});
问题是jqXHR 中没有responseJSON。
为什么任何其他异常(例如我之前使用的UnauthorizedException)在返回中生成responseJSON 而不是UnauthenticatedException?
如何使它与UnauthenticatedException 一起工作?
【问题讨论】:
-
检查响应到底是什么(例如使用浏览器的网络控制台)...我猜这是一个重定向,这意味着您已经配置了中间件的
unauthenticatedRedirect选项。 -
@ndm 你是对的,这似乎是一个重定向,我在
Application.php中有'unauthenticatedRedirect' => Router::url('/admin/users/login'),... 我该怎么做才能让它像UnauthorizedException这样的常规异常一样工作例如?
标签: php authentication cakephp cakephp-4.x