Symfony2可选无状态身份验证

时间:2016-02-24 11:20:35

标签: symfony

我有一个API,我通过它在每个HTTP请求中发送的密钥对用户进行身份验证。我的防火墙配置是这样的:

firewalls:        
  authentication_required:
    stateless: true
    simple_preauth:
      authenticator: my_authenticator
    provider: my_provider

对于某些URL,我允许匿名用户,在防火墙配置中使用security: false绕过身份验证。它看起来像:

firewalls:        
  authentication_not_required:
    stateless: true
    security: false

现在,我希望匿名用户可以访问某些URL,但是可以为现有用户进行身份验证。防火墙配置看起来像那样,但显然它不起作用:

firewalls:        
  my_area:
    stateless: true
    security: false
    simple_preauth:
      authenticator: my_authenticator
    provider: my_provider

有人知道该怎么做吗?

2 个答案:

答案 0 :(得分:2)

anonymous: ~是你的事。

firewalls:        
    my_area:
        stateless: true
        anonymous: ~
        simple_preauth:
            authenticator: my_authenticator
        provider: my_provider

答案 1 :(得分:1)

解决方法是按照PawełMikołajczuk的建议添加anonymous: ~,并在必要时修改验证者以绕过它,如symfony Cookbook中所述:http://symfony.com/doc/current/cookbook/security/api_key_authentication.html#only-authenticating-for-certain-urls

在我的例子中,我将一组允许的匿名路径传递给ApiKeyAuthenticator服务,然后在其createToken()函数的开头,检查当前路径是否允许进行匿名访问。

它看起来像:

// Allow some specific paths to have both anonymous and authenticated users
if (!$request->headers->has('X-Api-Key')) {
    foreach ($this->allowedAnonymousPaths as $path) {
        if ($this->httpUtils->checkRequestPath($request, $path)) {
            return;
        }
    }
}