Symfony2防火墙:重定向到注册表单而不是登录

时间:2014-06-23 14:56:53

标签: php security symfony authentication

我正在开发一个基于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也不是解决方案。

最好的解决办法是什么?

2 个答案:

答案 0 :(得分:2)

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

Using Symfony2's AccessDeniedHandlerInterface

此外,您可以通过配置组件配置服务,以便将要重定向的路由作为参数传递。

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

如果您这样做,您可以更改,如果您有更多用户,重定向回登录页面而不编辑任何课程。

答案 1 :(得分:2)

Nextar's answer引导我找到解决方案。

引用this question

  

只有在用户访问资源的权限不足时,才会调用access_denied_handler指向的服务。如果用户未经过身份验证,则永远不会调用access_dened_handler。在security.yml中为entry_point提供服务确实解决了问题

所以我最终得到了这个:

#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'));
        }
    }
}
相关问题