从登录页面限制或重定向登录用户

时间:2015-08-21 07:33:51

标签: php symfony

我使用的是Symfony 2.7,安装了FOSuserbundle,一切正常。我的用户正在创建,我可以使用它们登录,但登录用户可以进入登录页面,这对我来说似乎不合逻辑。我看了一些答案,发现我必须配置我的security.yml文件,但它仍然不起作用,任何人都可以进入登录页面。

我发现我必须设置

 - { path: ^/, role: ROLE_USER}

但这给了我一个重定向循环。

以下是我的内容

    firewalls:
    # disables authentication for assets and the profiler, adapt it according to your needs
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4

        logout:       true
        anonymous:    true
        # activate different ways to authenticate

        # http_basic: ~
        # http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate

        # form_login: ~
        # http://symfony.com/doc/current/cookbook/security/form_login_setup.html
access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/profile, role: ROLE_USER }
    - { path: ^/admin/, role: ROLE_ADMIN }

2 个答案:

答案 0 :(得分:1)

以这种方式覆盖tge SecurityController的loginAction:

class SecurityController extends BaseSecurityController
{
public function loginAction(Request $request)
{
   if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') { 
   return $this->redirect($this->generateUrl('any_route_you_want'))
}

  return parent::loginAction($request);
 }
}

修改:要了解如何覆盖Bundle的任何部分,this会有所帮助

答案 1 :(得分:0)

Allready试过这个解决方案? FOSUserBundle redirect from login page after logged in

PHP:

  

您可以覆盖FOSUserBundle \ Controller \ SecurityController并在loginAction的顶部添加以下代码。

use Symfony\Component\HttpFoundation\RedirectResponse;
// ...
public function loginAction(Request $request)
{
$securityContext = $this->container->get('security.context');
$router = $this->container->get('router');
if ($securityContext->isGranted('ROLE_ADMIN')) {
    return new RedirectResponse($router->generate('admin_home'), 307);
}
if ($securityContext->isGranted('ROLE_USER')) {
    return new RedirectResponse($router->generate('user_home'), 307);
}
// ... 

YAML:

  

更简单的解决方案是将这两行添加到app / config / security.yml:

     

always_use_default_target_path&amp; default_target_path,例如:

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            login_path: /login
            check_path: /login_check
            always_use_default_target_path: false
            default_target_path:            /your/start/path/