Symfony2可选无状态身份验证
我有一个API,通过用户在每个HTTP请求中发送的密钥对用户进行身份验证。我的防火墙配置如下:Symfony2可选无状态身份验证,symfony,Symfony,我有一个API,通过用户在每个HTTP请求中发送的密钥对用户进行身份验证。我的防火墙配置如下: firewalls: authentication_required: stateless: true simple_preauth: authenticator: my_authenticator provider: my_provider // Allow some specific paths to have both anonymous
firewalls:
authentication_required:
stateless: true
simple_preauth:
authenticator: my_authenticator
provider: my_provider
// 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;
}
}
}
对于某些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
有人知道怎么做吗?
匿名:~
是你的事
firewalls:
my_area:
stateless: true
anonymous: ~
simple_preauth:
authenticator: my_authenticator
provider: my_provider
解决方案是按照PawełMikołajczuk的建议添加
匿名:~
,并在必要时修改验证器以绕过它,如symfony Cookbook中所述:
在我的例子中,我将允许的匿名路径数组传递给ApiKeyAuthenticator服务,然后在其createToken()函数的开头,检查当前路径是否允许匿名访问
它看起来像:
firewalls:
authentication_required:
stateless: true
simple_preauth:
authenticator: my_authenticator
provider: my_provider
// 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;
}
}
}
谢谢,在我的例子中,它不仅仅适用于
匿名:~
。我还修改了验证器以对路径执行检查,如Symfony Cookbook中所述,这样它就工作了:。