2014-06-23 43 views
2

我正在基于Symfony2开发一个简单的商店(用于编译商品)。Symfony2防火墙:重定向到注册表单而不是登录

将商品添加到购物车后,用户可以继续提供其商品的摘要,然后请求编译的商品。

security: 
firewalls: 
    secured_area: 
     pattern: ^/ 
     anonymous: ~ 
     provider: default 
     form_login: 
      login_path: acme_security_login_route 
      check_path: acme_security_login_check_route 
      csrf_provider: form.csrf_provider 
     logout: ~ 

    default: 
     anonymous: ~ 

access_control: 
    - { path: ^/request-offer, roles: ROLE_CLIENT } 

providers: 
    default: 
     entity: { class: AcmeShopBundle:User } 

encoders: 
    Symfony\Component\Security\Core\User\User: plaintext 
    Acme\ShopBundle\Entity\User: 
     algorithm: bcrypt 
     cost:  15 

这意味着,如果客户端登录,他会直接去总结,如果没有,他会被重定向到登录页面:

摘要页由以下防火墙保护。

现在,由于客户更有可能成为新客户,我希望重定向到注册表单。

SecurityBundle Configuration Reference中描述的选项不允许这样做。 当然,改变login_path也不是解决方案。

什么是最好的解决方案?

回答

1

Nextar's answer将我引向解决方案。

报价this question

由access_denied_handler指出该服务,如果用户有非充分的权限访问该资源时才会调用。如果用户未完全通过身份验证,则始终不会调用access_dened_handler。提供服务的security.yml到入口点没有实际解决问题

所以我结束了这一点:

#services.yml 
acme.security.entry_point.class: ArtCube\ShopBundle\Service\EntryPointHandler 

services: 
    acme.security.entry_point_handler: 
     class: %acme.security.entry_point.class% 
     arguments: 
      router:  @router 

然后我说这个服务我security.yml,之后logout: ~线(见初始问题):

entry_point: art_cube_shop.security.entry_point_handler 

,并创建了服务:

// Acme/ShopBundle/Service/EntryPointHandler.php 

use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Routing\Router; 
use Symfony\Component\Security\Core\Exception\AuthenticationException; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException; 
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; 

class EntryPointHandler implements AuthenticationEntryPointInterface { 

    protected $router; 

    public function __construct(Router $router) 
    { 
     $this->router = $router; 
    } 

    public function start(Request $request, AuthenticationException $authException = null) 
    { 
     if($authException instanceof InsufficientAuthenticationException) 
     { 
      return new RedirectResponse($this->router->generate('acme_security_registration_route')); 
     } 
     else 
     { 
      return new RedirectResponse($this->router->generate('acme_security_login_route')); 
     } 
    } 
} 
1

在我看来,一个不错的解决方案是添加一个自己的AccessDeniedExceptionHandler,如何做到这一点在这里解释。

Using Symfony2's AccessDeniedHandlerInterface

更进一步,你可以通过做配置组件配置的服务,让您传递作为参数来重定向路径。

http://symfony.com/doc/current/components/config/definition.html

如果你这样做,你可以改变的,如果你有更多的用户,要回重定向没有编辑任何类到登录页面。

+0

仅当用户访问资源的权限不足时才会调用access_denied_handler,但如果他根本没有进行身份验证,则仅调用access_denied_handler。 但是你的回答让我想到解决方案,谢谢! – mpbzh

相关问题