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


Restrict or redirect logged in users from login page

我使用的是Symfony 2.7,安装了FOSuserbundle,一切正常。我的用户正在创建中,我可以登录他们,但是登录的用户可以进入登录页面,这对我来说似乎不合乎逻辑。我找了一些答案,发现我必须配置我的安全。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 }

重写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);
 }
}

Edit:要学习如何覆盖Bundle的任何部分,这将很有帮助

已经尝试了这个解决方案吗?FOSUserBundle在登录后从登录页面重定向

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,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/