我在 cakephp 4 中使用插件身份驗證 2。
我想UnauthenticatedException在用戶未登錄和 ajax 請求的情況下拋出一個。
目標是在 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();
}
});
問題是沒有responseJSONin jqXHR。
為什么在回傳中UnauthorizedException生成任何其他例外(例如我之前使用的例外)responseJSON而不是UnauthenticatedException?
怎么做才能讓它作業UnauthenticatedException?
uj5u.com熱心網友回復:
默認情況下,身份驗證中間件會重新拋出未經身份驗證的例外,除非您配置該unauthenticatedRedirect選項,否則它將相應地將這些例外轉換為重定向。
如果您需要同時支持 HTML 和 JSON 請求/回應,那么您可以例如根據當前請求動態配置或不配置unauthenticatedRedirect選項,例如在您的Application::getAuthenticationService()方法中執行以下操作:
$service = new AuthenticationService();
$accepts = array_map('trim', explode(',', $request->getHeaderLine('Accept')));
$isJsonRequest = in_array('application/json', $accepts, true);
if (!$isJsonRequest) {
// service config for non-JSON requests
$service->setConfig([
'unauthenticatedRedirect' => /* ...*/,
'queryParam' => 'redirect',
]);
}
或者手動評估標頭,要求request是一個實體\Cake\Http\ServerRequest并使用它的is()方法:
assert($request instanceof \Cake\Http\ServerRequest);
if (!$request->is('json')) {
$service->setConfig([
'unauthenticatedRedirect' => [/* ...*/],
'queryParam' => 'redirect',
]);
}
另請注意,默認情況下,身份驗證組件將要求存在身份并相應地拋出例外,您不必自己這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/391575.html
標籤:php 验证 蛋糕 cakephp-4.x
