Symfony access control配置引发登录页ERR_TOO_MANY_REDIRECTS问题
解决Symfony中已认证用户访问登录页导致的重定向循环问题
你当前的配置仅允许匿名用户访问app_login路由,但当已认证用户尝试访问时,Symfony安全系统会拒绝该请求,并默认重定向到登录页,由此形成无限重定向循环,触发ERR_TOO_MANY_REDIRECTS错误。
以下是两种可行的解决方案:
方案一:通过access_control配置重定向
调整access_control的规则顺序,优先匹配已认证用户访问app_login的场景,将其重定向到首页(或其他指定页面),再允许匿名用户访问。修改后的security.yaml配置如下:
firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: lazy: true provider: app_user_provider custom_authenticator: App\Security\LoginFormAuthenticator logout: path: app_logout target: app_home access_control: # 已认证用户访问登录页时重定向到首页 - { route: app_login, roles: ROLE_USER, redirect_to: app_home } # 允许匿名用户访问登录页 - { route: app_login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
注意:
access_control的规则是从上到下匹配,因此需将已认证用户的规则放在前面,确保优先触发。
方案二:在登录控制器中手动处理
在登录控制器的login方法里,先检查用户是否已完成认证,若已认证则直接重定向到首页,避免进入登录页面逻辑:
// src/Controller/SecurityController.php use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; class SecurityController extends AbstractController { public function login(Security $security, AuthenticationUtils $authenticationUtils): Response { // 若用户已认证,直接重定向到首页 if ($security->isGranted('IS_AUTHENTICATED_FULLY')) { return $this->redirectToRoute('app_home'); } // 原有登录逻辑 $error = $authenticationUtils->getLastAuthenticationError(); $lastUsername = $authenticationUtils->getLastUsername(); return $this->render('security/login.html.twig', [ 'last_username' => $lastUsername, 'error' => $error, ]); } }
内容的提问来源于stack exchange,提问作者Konteye
相关产品推荐
相关产品推荐

