简体   繁体   中英

Symfony2 Dynamic Logout Target?

I have a working Symfony2 application that properly logs users in and out, and when logging out it properly redirects the user to the home page.

I'd like to keep them on their current page when the log out, only without their logged-in privileges.

My question is:

Can I dynamically set the page the user is directed to when they log out?

What you need is a logout success handler.

Define the logout handler in the security.yml:

security:
    firewalls:
        admin_area:
            logout:
                success_handler: acme.security.logout_success_handler

And the handler goes like this:

namespace Acme\Bundle\SecurityBundle\Handler;

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerAware;

class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
    {
    public function onLogoutSuccess(Request $request)
    {
        // dynamic route logic

        return new RedirectResponse($this->container->get('router')->generate('dynamic_route_name'));
    }
}

Btw... Please remove the unwanted imports and Hope this helps! :D

Here is the services.yml

services:
    acme.security.logout_success_handler:
        class: Acme\Bundle\SecurityBundle\Handler\LogoutSuccessHandler
        calls:
            - [ setContainer, [ @service_container ] ]

I needed a Logout Success Handler, and this is how I implemented it:

security.yml :

logout:
    success_handler: acme.security.logout_success_handler

config.yml :

services:
    acme.security.logout_success_handler:
        class: Acme\DefaultBundle\Handler\LogoutSuccessHandler

Symfony/src/Acme/DefaultBundle/Handler/LogoutSuccessHandler.php:

<?php

namespace Acme\DefaultBundle\Handler;

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerAware;

class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
{
    public function onLogoutSuccess(Request $request)
    {
        $target_url = $request->query->get('target_url')
                      ? $request->query->get('target_url')
                      : "/";
        return new RedirectResponse($target_url);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM