You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony自定义登出:实现不同路径登出跳转至不同页面

解决方案:自定义登出成功处理器实现动态跳转

不用配置多个防火墙,通过自定义登出成功处理器就能轻松实现按当前路径动态跳转的需求,具体步骤如下:

1. 创建自定义LogoutSuccessHandler

在src/Security/目录下新建CustomLogoutSuccessHandler.php,实现LogoutSuccessHandlerInterface,在方法内根据当前请求路径判断跳转目标:

<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;

class CustomLogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
    public function __construct(private UrlGeneratorInterface $urlGenerator)
    {
    }

    public function onLogoutSuccess(Request $request): RedirectResponse
    {
        $currentPath = $request->getPathInfo();
        
        // 匹配 /dev/{id} 格式的路径
        if (preg_match('#^/dev/(\d+)#', $currentPath, $matches)) {
            $id = $matches[1];
            return new RedirectResponse($this->urlGenerator->generate('app_home', ['id' => $id]));
        }
        
        // 默认跳转到登录页(覆盖 /user 开头及其他所有路径场景)
        return new RedirectResponse($this->urlGenerator->generate('app_login'));
    }
}

2. 修改security.yaml配置

替换原来固定的target配置,指定使用自定义处理器:

# security.yaml
security:
    enable_authenticator_manager: true
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\Dimitry:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\Dimitry
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            lazy: true
            provider: app_user_provider
            custom_authenticator: App\Security\LoginAuthenticator
            logout:
                path: app_logout
                success_handler: App\Security\CustomLogoutSuccessHandler

3. 调整SecurityController的logout方法

Symfony的登出逻辑会被防火墙拦截,因此logout方法无需自行编写跳转逻辑,恢复默认注释即可:

#[Route(path: '/logout', name: 'app_logout')]
public function logout()
{
    // 此处无需编写逻辑,防火墙会自动处理登出,跳转逻辑由自定义处理器接管
    throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}

完成以上配置后,用户在/user开头的页面登出时会跳转至登录页;在/dev/{id}格式的页面登出时,会自动跳转至对应id的/home/{id}页面,完全匹配你的需求。

内容的提问来源于stack exchange,提问作者STACK_MIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:55:22