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

Symfony已认证用户访问/login路由时如何实现重定向?

已认证用户访问/login路由时的重定向问题

问题背景

用户已完成认证,但通过某种方式回到/login路由时,登录表单仍会显示,需要实现自动重定向到用户的起始页或仪表盘。尝试了以下代码,但出现错误。

尝试的代码

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        
        if ($this->isGranted('IS_AUTHENTICATED_FULLY') || $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            
            $user = $this->getUser();
            $startpage = $user->getStartpage();

            if ( $startpage ) {
                $targetUrl = $this->router->generate($startpage);
            } else {
                $targetUrl = $this->router->generate('user_dashboard');
            }

            return $this->redirect($targetUrl);
            //return new RedirectResponse($targetUrl);

        }
        
        return $this->render('security/login_microsoft.html.twig', [
            'error' => $authenticationUtils->getLastAuthenticationError(),
            'last_username' => $authenticationUtils->getLastUsername(),
        ]);            

    }
}

出现的错误

Warning: Undefined property: App\Controller\SecurityController::$router

解决方案

报错原因是AbstractController中并没有$router这个属性,你可以通过两种方式修复:

方式一:使用AbstractController内置的generateUrl方法

直接替换$this->router->generate()为$this->generateUrl(),这是AbstractController提供的快捷方法,无需手动注入路由服务:

if ( $startpage ) {
    $targetUrl = $this->generateUrl($startpage);
} else {
    $targetUrl = $this->generateUrl('user_dashboard');
}

方式二:注入RouterInterface服务

如果需要显式使用路由服务,可以在方法参数中注入Symfony\Component\Routing\RouterInterface:

use Symfony\Component\Routing\RouterInterface;

// ...

public function login(AuthenticationUtils $authenticationUtils, RouterInterface $router): Response
{
    // ...
    if ( $startpage ) {
        $targetUrl = $router->generate($startpage);
    } else {
        $targetUrl = $router->generate('user_dashboard');
    }
    // ...
}

两种方式都能解决$router未定义的问题,实现已认证用户访问/login路由时自动重定向到指定页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:22:45