Symfony2 - Access for Login and Register page for Anonymous only not Users

后端 未结 2 2075
名媛妹妹
名媛妹妹 2021-01-18 03:18

I have this website with a login form and after I successfully logged in, I am redirected to the index. But when I click the back button, it lets me still view the login for

相关标签:
2条回答
  • 2021-01-18 03:40

    With symfony 4 you can solve it with allow_if :

    access_control:
    - { path: /login, allow_if: "!is_authenticated()" }
    

    here's the list of expressions available within allow_if string http://symfony.com/doc/current/security/expressions.html#security-expression-variables

    0 讨论(0)
  • 2021-01-18 03:48

    This may not be the best or proper way to do it, but its been the only way I could figure it out.

    In my loginAction method I do this (see the $secured variable). If the user session is authenticated then I redirect them to the home/index page. I don't know of a way to do it via the firewall config because I don't believe the login page would ever have a firewall attached to it.

    /**
     * @Route("/login", name="login")
     * @Template()
     */
    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();
    
        // if the session is secured (user is logged in) 
        // then $secured will be an object with various user information.
        $secured = unserialize($session->get('_security_secured'));
        if ($secured) {
            return $this->redirect($this->generateUrl('home'));
        }
    
        // 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);
        }
    
        return array(
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
            'embed'         => $request->isXmlHttpRequest()
        );
    }
    
    0 讨论(0)
提交回复
热议问题