[英]What is the proper way to call class functions using Symfony's router and http-foundation components?
[英]What’s the proper way to handle an AJAX call behind Symfony 4 firewall?
我需要將AJAX請求發送到我的用戶經過身份驗證的網站的一部分。 不幸的是,Symfony 4拒絕了這些請求(並將它們發送到登錄頁面),因為它沒有將其檢測為對我的控制器/路由的身份驗證訪問。
如何確保您的Ajax請求通過Symfony 4訪問控制? 在我的security.yaml中,我將安全性配置如下:
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/profile, roles: ROLE_USER }
我需要使用ajax調用來訪問/ profile / update。 如何為symfony提供憑證?
謝謝!
您的控制器方法將Ajax調用重定向到登錄頁面,因為您的JS不發送憑據(讀取:cookie)。
如果您使用提取,請使用credentials
:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
參見https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
如果您使用其他方式創建Ajax調用,請使用一些JS代碼更新您的問題,並告訴我:)。
如果在執行XMLHttpRequest('ajax')時不想將用戶重定向到登錄頁面,請使用此偵聽器發送403響應:
class AjaxAuthenticationListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => [
['onCoreException', 10],
],
];
}
public function onCoreException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$request = $event->getRequest();
if (! $request->isXmlHttpRequest()) {
return;
}
if (! ($exception instanceof AuthenticationException) && ! ($exception instanceof AccessDeniedException)) {
return;
}
$event->setResponse(new Response('No access', 403));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.