3

有没有办法将已经登录的用户重定向到主页?例如,那些带有 cookie 或“记住我”的人?

我在我的“loginController”中试过这个,但它不起作用

public function loginAction()
{
    $request = $this->getRequest();
    $session = $request->getSession();
   // $user = new Usuario();

    // get the login error if there is one
    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
        $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
    }
    $securityContext = $this->container->get('security.context');
    if( $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){
       $this->redirect($this->generateUrl('MonsePanelBundle_homepage'));
    }
    return $this->render('UsuariosBundle:Security:login.html.twig', array(
        // last username entered by the user
        'last_username' => $session->get(SecurityContext::LAST_USERNAME),
        'error'         => $error,
    ));
}

我已经阅读了所有其他类似的问题,但到目前为止还没有运气......

这是我的 security.yml 以防万一……

security:
encoders:
   Monse\UsuariosBundle\Entity\Usuario:
        algorithm: sha512
        encode-as-base64: true
        iterations: 10

role_hierarchy:
    ROLE_ADMIN: [ROLE_USER]
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

providers:
    user_db:
        entity: { class: Monse\UsuariosBundle\Entity\Usuario, property: usuario }

firewalls:
    main:
        pattern: /.*
        provider: user_db
        form_login:
            login_path: /login
            check_path: /login_check
            remember_me: true
            default_target_path: /panel
        logout:
            path: /logout
            target: /login
        remember_me:
            key: MiClaveSegura
            lifetime: 1800
            path: /.*
            domain: ~
        security: true
        anonymous: true
access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/panel, roles: [ROLE_SUPER_ADMIN, ROLE_ADMIN, ROLE_USER] }
4

3 回答 3

4

您错过了重定向行中的“返回”

$securityContext = $this->container->get('security.context');
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')){
    return $this->redirect($this->generateUrl('MonsePanelBundle_homepage'));
}
于 2014-11-18T11:16:06.690 回答
3

有时您需要在每个操作之前在控制器上执行一个方法,有时在多个控制器上执行。即,如果您想检查用户是否已登录。

我的代码是https://matt.drollette.com/2012/06/calling-a-method-before-every-controller-action-in-symfony2/的自定义

如果将其应用于控制器,它会检查用户是否已登录。如果是,则不会显示登录页面。但您可以将用户重定向到项目的任何页面


在 UsuariosBundle 旁边创建一个新的 Bundle,将其命名为 CoreBundle。在这个包中创建两个文件夹 EventListener 和 Model。在模型中创建:

interface InitializableControllerInterface
{
    public function initialize(Request $request, 
                               SecurityContextInterface $security_context, 
                               FilterControllerEvent $event);
}

在 EventListener 创建:

class BeforeControllerListener
{
    private $security_context;

    public function __construct(SecurityContextInterface $security_context)
    {
        $this->security_context = $security_context;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            // not a object but a different kind of callable. Do nothing
            return;
        }

        $controllerObject = $controller[0];

        // skip initializing for exceptions
        if ($controllerObject instanceof ExceptionController) {
            return;
        }

        if ($controllerObject instanceof InitializableControllerInterface) {
            // this method is the one that is part of the interface.
            $controllerObject->initialize($event->getRequest(),
                                          $this->security_context, $event);
        }
    }
}

在类中,您不需要进行任何自定义。只需复制并粘贴它们。假设您有一个 DefaultController,其中索引操作默认指向登录页面。您可能希望阻止已登录的用户查看登录页面,因为它只有促销内容:

class DefaultController extends Controller 
                        implements InitializableControllerInterface {

    /* Do not show landing page if user is logged in */

    public function initialize(Request $request, 
                               SecurityContextInterface $security_context, 
                               FilterControllerEvent $event) {

        $parent = $this;

        $securityContext = $this->container->get('security.context');

        if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY') ||
            $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {

            if ($parent->container->get('request')->get('_route') != 
                                                   'my_homepage') {
                //nothing
            } else {
                $event->setController(function() use ($parent) {
                return new RedirectResponse(
                           $parent->generateUrl('my_user'));
                        });
            }
        }
    }

   //your code
}

希望有帮助!

于 2013-01-27T09:31:41.440 回答
0

我认为你需要像这样实现你的安全监听器

 public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
    }
 public function onKernelResponse(FilterResponseEvent $event)
    {
        if ($this->security->isGranted('ROLE_SUPER')) {
            $response = new RedirectResponse($this->router->generate('route1'));
        } 

        elseif ($this->security->isGranted('ROLE_USER')) {
            $response = new RedirectResponse($this->router->generate('route2'));
        } 


        $event->setResponse($response);
    }

在这里查看更多信息http://symfony.com/doc/2.0/components/event_dispatcher/introduction.html

于 2013-01-27T09:01:00.910 回答