【问题标题】:Symfony security return 401 response instead of redirectSymfony 安全返回 401 响应而不是重定向
【发布时间】:2013-09-10 20:06:01
【问题描述】:

我正在编写一个带有 ajax 身份验证的 ajax 应用程序,现在我开始使用 silex 中的 symfony 安全组件来处理身份验证/授权。
用简单的配置做一个简单的测试,我去防火墙旁边的一个保护区,我得到的响应是重定向到 /login 页面,但我的应用程序中需要的是一个 401 响应,其中包含可能的附加信息(在标题中或 json body) 如何登录。

$app['security.firewalls'] = [
    'api' => [
        'pattern' => '^/api',
        'logout' => ['logout_path'=>'/auth/logout'],
        'users' => $app->share(function(Application $app) {
            return new MyUserProvider();
        })
    ]
];

编辑:我得到了提示,但我不确定如何使用它。使用AuthenticationEntryPointInterface 实现一个入口点我可以告诉 api 如何回答未经身份验证的请求并为用户提供身份验证所需的指令。这可能是我带有登录说明的 401 响应。

【问题讨论】:

    标签: php security authentication symfony silex


    【解决方案1】:

    您需要的是一个 AuthenticationEntryPoint 处理程序。 简单例子:

    class AuthenticationEntryPoint implements AuthenticationEntryPointInterface {
    
    /**
     * Starts the authentication scheme.
     *
     * @param Request $request The request that resulted in an AuthenticationException
     * @param AuthenticationException $authException The exception that started the authentication process
     *
     * @return Response
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $array = array('success' => false);
        $response = new Response(json_encode($array), 401);
        $response->headers->set('Content-Type', 'application/json');
    
        return $response;
    }
    }
    

    在 services.xml 文件中将类注册为服务:

    <parameters>
        <parameter key="authentication_entry_point.class">YourNameSpace\AuthenticationEntryPoint</parameter>
    </parameters>
    
    <services>
        <service id="authentication_entry_point" class="%authentication_entry_point.class%"/>
    </services>
    

    并在 security.yml 文件中做一个小改动:

    security:
      firewalls:
        somename:
          entry_point: authentication_entry_point
    

    【讨论】:

      【解决方案2】:

      我能够像这样覆盖“api”防火墙下“form”类型的默认入口点:

      $app['security.entry_point.api.form'] = $app->share(function () use ($app) {
          return new MyAuthenticationEntryPoint();
      });
      

      那么只需要实现AuthenticationEntryPointInterface:

      http://symfony.com/doc/current/components/security/firewall.html#entry-points

      看一下 symfony 的实现来了解一下:

      Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint
      

      另外,可能值得检查一下 silex 安全服务提供商,看看他们如何将其注入到默认实现的“security.entry_point.form._proto”中。

      Silex\Provider\SecurityServiceProvider
      

      【讨论】:

        猜你喜欢
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-09
        • 2015-11-11
        • 2015-08-05
        • 2013-02-12
        相关资源
        最近更新 更多