6

当用户尝试访问没有令牌的页面时,我试图防止重定向到登录页面,我有单页应用程序,我只是将 ajax 请求放在防火墙下,当用户在没有令牌的情况下执行 ajax 时,我希望 ajax 返回禁止的异常,所以我将能够在客户端捕获它

当前 ajax 返回“Found”,因为请求被重定向到登录页面

到目前为止我还没有在食谱中找到解决方案我不想使用 api 令牌,只发送异常而不是重定向到登录

4

1 回答 1

8

您需要为entry_point您的防火墙定义一个,以便您返回未经授权的响应。有关入口点的信息可以在此处的文档中找到。如果将来有请求,我将在此处复制该段落。

当用户根本没有通过身份验证时(即令牌存储还没有令牌时),防火墙的入口点将被调用以“启动”身份验证过程。入口点应该实现AuthenticationEntryPointInterface,它只有一个方法:start()。此方法接收当前的 Request 对象和触发异常侦听器的异常。该方法应返回一个 Response 对象。例如,这可能是包含登录表单的页面,或者在基本 HTTP 身份验证的情况下,是带有 WWW-Authenticate 标头的响应,它将提示用户提供他们的用户名和密码。

因此,为了做到这一点,您必须创建一个将被定义为服务的类。

它应该如下所示:

namespace MyBundle\Service;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class CustomEntryPoint implements AuthenticationEntryPointInterface
{

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $response = new Response("", Response::HTTP_UNAUTHORIZED);

        return $response;
    }

}

在你的services.yml文件中

services:
    service.entry_point:
        class: MyBundle\Service\CustomEntryPoint

最后将服务 ID 传递service.entry_point给文件部分中的entry_point选项。firewallsecurity.yml

这应该可以解决问题。

于 2015-06-27T22:26:28.210 回答