Symfony2: how to log user out manually in controller?

后端 未结 5 578
清酒与你
清酒与你 2020-11-28 23:35

i would like to do something like that in controller to log user out:

$user = $this->get(\'security.context\')->getToken()->getUser();
$user->lo         


        
相关标签:
5条回答
  • 2020-11-28 23:45

    Logout in Symfony2 is handled by so called logout handler which is just a lister that is executed when URL match pattern from security configuration, ie. if URL is let's say /logout then this listener is executed. There are two build-in logout handlers:

    1. CookieClearingLogoutHandler which simply clears all cookies.
    2. SessionLogoutHandler which invalidates the session

    All you have to do is the very same the last one does. You can achieve it by simply calling:

    Legacy Symfony

    $this->get('security.context')->setToken(null);
    $this->get('request')->getSession()->invalidate();
    

    Symfony 2.6

    $this->get('security.token_storage')->setToken(null);
    $this->get('request')->getSession()->invalidate();
    

    Warning

    This will only work when remember me functionality is disabled. In other case, user will be logged in back again by means of a remember me cookie with the next request.

    Please consider the extended solution if you are using remember me functionality: https://stackoverflow.com/a/28828377/1056679

    0 讨论(0)
  • 2020-11-28 23:48

    If rememberme functionality is enabled for your site you should also clean rememberme cookie:

        $this->get('security.context')->setToken(null);
        $this->get('request')->getSession()->invalidate();
    
        $response = new RedirectResponse($this->generateUrl('dn_send_me_the_bundle_confirm', array(
                    'token' => $token
                    )));
        // Clearing the cookies.
        $cookieNames = [
            $this->container->getParameter('session.name'),
            $this->container->getParameter('session.remember_me.name'),
        ];
        foreach ($cookieNames as $cookieName) {
            $response->headers->clearCookie($cookieName);
        }
    
    0 讨论(0)
  • 2020-11-29 00:00

    Invalidating the user's session might cause some unwanted results. Symfony's firewall has a listener that always checks and refreshes the user's token. You could just do a redirect to the default logout route that you have specified in your firewall.yml (or security.yaml)

    In Controller you can do this:

    $this->redirect($this->generateUrl('your_logout_url'));
    

    If you don't know the name of the logout route (your_logout_url), you can get it from the Symfony console by using this command:

    app/console router:match /logout
    

    Or newer Symfony versions:

    bin/console router:match /logout
    

    :)

    0 讨论(0)
  • 2020-11-29 00:05

    In case you are using symfony 4.x (I haven't tested other versions, so it still might work), you may want to use the internal logout handler of symfony (highly recommended, as it will take care of everything for you in a clean way, cookies and all). You don't need to write too much code for that either, you can simply emulate a logout request:

    ... // Some code, that leads you to force logout the user 
    // Emulating logout request
    $logoutPath = $this->container->get('router')->generate('app_logout');
    $logoutRequest = Request::create($logoutPath);
    $logoutResponse = $this->container->get('http_kernel')->handle($logoutRequest);
    // User is logged out now
    ... // Stuff to do after logging out, eg returning response
    

    This will make symfony do the request response flow, thus it will call the logout handler internally. This method allows you to proceed to further custom code. Otherwise, if you invoked only the logout listener here, you would have to return the usual logout response, that now is in $logoutResponse. Optionally, if you want to return it, you would also simply:

    return $logoutResponse;
    
    0 讨论(0)
  • 2020-11-29 00:07

    We have to set user as an anonymous user when logging out. Then we can use
    $token->getUser()->getRoles(); in controller or {% if is_granted('ROLE_USER') %} in the twig template.

    use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
    ...
    //$providerKey = $this->container->getParameter('fos_user.firewall_name');
    $token = new AnonymousToken($providerKey, 'anon.');
    $this->get('security.context')->setToken($token);
    $this->get('request')->getSession()->invalidate();
    
    0 讨论(0)
提交回复
热议问题