Symfony 6.3.12中通过SimpleSAMLphp获取用户信息实现程序化登录后会话无法持久化的问题求助
Symfony 6.3.12中通过SimpleSAMLphp获取用户信息实现程序化登录后会话无法持久化的问题求助
各位好,我在Symfony 6.3.12项目里对接SimpleSAMLphp实现微软SAML登录时,碰到了一个会话持久化的棘手问题,具体情况如下:
问题现象
- 当我通过
$userInfo = $this->samlMSAuth($sp);获取用户信息后,调用$security->login()完成程序化登录,返回首页时用Symfony调试器查看,用户确实处于登录状态; - 但只要跳转到其他页面,用户就立刻变成未登录状态了;
- 如果我去掉
$userInfo = $this->samlMSAuth($sp);这段代码,直接硬编码邮箱查询用户并执行程序化登录,会话就能正常持久化,所有页面都能保持登录状态。
代码相关细节
我的SAML控制器代码如下:
class SamlController extends AbstractController { private LoggerInterface $logger; private EntityManagerInterface $entityManager; private UserPasswordHasherInterface $userPasswordHasher; private UserAuthenticatorInterface $userAuthenticator; public function __construct(LoggerInterface $logger, EntityManagerInterface $entityManager, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator) { $this->logger = $logger; $this->entityManager = $entityManager; $this->userPasswordHasher = $userPasswordHasher; $this->userAuthenticator = $userAuthenticator; } #[Route('/saml/login', name: 'saml_login')] public function saml(Request $request, Security $security, string $sp = "default-sp"): Response { $session = $request->getSession(); $userInfo = $this->samlMSAuth($sp); // 实际应该用$userInfo里的邮箱查询,这里暂时硬编码测试 $user = $this->entityManager->getRepository(Zuser::class)->findOneBy(['email' => 'email@example.com']); $security->login($user, 'security.authenticator.form_login.main', 'main'); return $this->redirect('/home'); } #[Route('/saml/logout', name: 'saml_logout')] public function samlLogout(Security $security): Response { $security->logout(false); return $this->redirectToRoute('saml_login'); } public function samlMSAuth(string $sp = "default-sp") { $as = new \SimpleSAML\Auth\Simple($sp); $as->requireAuth(); // 这里会跳转到微软登录页,验证完成后返回应用 $attributes = $as->getAttributes(); $email = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']; $surname = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname']; $givenname = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname']; $userInfo = [ "Email" => $email[0], "Surname" => $surname[0], "Givenname" => $givenname[0], ]; return $userInfo; } }
已尝试的排查和解决方法
- 检查会话状态:登录前会话是空的,登录后我手动尝试将认证token序列化存入会话:
$request->getSession()->set('_security_main', serialize($token));,但问题依旧存在; - 定位问题触发点:只要去掉
$as->requireAuth()触发的外部跳转逻辑,会话就能正常持久化,说明问题肯定和SimpleSAML的跳转与Symfony会话的交互有关。
想请教各位大佬,有没有遇到过类似的问题?或者能给我一些排查方向和解决思路?
备注:内容来源于stack exchange,提问作者Owen Chen
相关产品推荐
相关产品推荐

