如何通过ITFoxTec读取IdP返回的SAML响应并获取邮箱
从ITFoxTec Saml2AuthnResponse中获取邮箱属性
你可以通过两种方式从解析后的SAML响应中提取邮箱属性,以下是具体实现方法:
方法1:直接读取Attributes字典
ITFoxTec的Saml2AuthnResponse内置了Attributes字典,以SAML属性的Name(即OID)作为键,你可以直接通过目标属性的OID获取对应值:
// 在binding.Unbind执行完成后添加这段代码 string email = null; if (saml2AuthnResponse.Attributes.TryGetValue("urn:oid:1.3.6.1.4.1.5923.1.1.1.6", out var emailAttribute)) { email = emailAttribute?.FirstOrDefault(); }
方法2:通过ClaimsPrincipal获取声明
binding.Unbind执行后,saml2AuthnResponse.ClaimsPrincipal已包含所有解析出的声明,你可以通过属性的OID作为ClaimType查找值:
// 在binding.Unbind执行完成后添加这段代码 var emailClaim = saml2AuthnResponse.ClaimsPrincipal.Claims .FirstOrDefault(c => c.Type == "urn:oid:1.3.6.1.4.1.5923.1.1.1.6"); string email = emailClaim?.Value;
集成到你的完整代码中
修改后的AssertionConsumerService方法示例:
[Route("AssertionConsumerService")] public async Task<IActionResult> AssertionConsumerService() { var binding = new Saml2PostBinding(); var saml2AuthnResponse = new Saml2AuthnResponse(config); binding.ReadSamlResponse(Request.ToGenericHttpRequest(validate: true), saml2AuthnResponse); if (saml2AuthnResponse.Status != Saml2StatusCodes.Success) { throw new AuthenticationException($"SAML Response status: {saml2AuthnResponse.Status}"); } binding.Unbind(Request.ToGenericHttpRequest(validate: true), saml2AuthnResponse); // 提取邮箱属性 string email = null; if (saml2AuthnResponse.Attributes.TryGetValue("urn:oid:1.3.6.1.4.1.5923.1.1.1.6", out var emailAttribute)) { email = emailAttribute?.FirstOrDefault(); } await saml2AuthnResponse.CreateSession(HttpContext, claimsTransform: (claimsPrincipal) => ClaimsTransform.Transform(claimsPrincipal)); var relayStateQuery = binding.GetRelayStateQuery(); var returnUrl = relayStateQuery.ContainsKey(relayStateReturnUrl) ? relayStateQuery[relayStateReturnUrl] : Url.Content("~/na"); // 传入邮箱到自定义登录服务 var username = saml2AuthnResponse.NameId; var user = _loginService.Login(username.ToString(), email); await HttpContext.SignInAsync(user); return Redirect(returnUrl); }
注意事项
- 必须使用属性的
Name(即OID字符串)作为查询键,而非FriendlyName,ITFoxTec默认以属性的Name字段作为字典索引标识。 - 如果需要将OID映射为更直观的ClaimType(比如
Email),可以在ClaimsTransform.Transform方法中添加自定义映射逻辑。
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

