如何在Spring Boot控制器中获取SAML2的RelayState?
在Spring SAML2环境中获取RelayState的方法
在Spring Security SAML2模块(替代原Spring SAML 1)中,RelayState的获取方式和SAML1有所不同,以下是两种在控制器方法中获取RelayState的可行方案:
方案1:直接在控制器方法参数中注入Saml2AuthenticationToken
Spring Security会自动将当前认证上下文的Saml2AuthenticationToken绑定到方法参数中,你可以从其details属性中提取RelayState:
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SamlController { @GetMapping("/saml/callback") public String handleSamlCallback(Saml2AuthenticationToken authentication) { // 从认证token的details中获取RelayState String relayState = authentication.getDetails().getRelayState(); // 后续业务逻辑处理 return "RelayState: " + relayState; } }
方案2:通过SecurityContextHolder获取
如果你习惯使用SecurityContextHolder的方式,可将认证对象强转为Saml2AuthenticationToken后获取RelayState,逻辑和SAML1类似但类型不同:
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SamlController { @GetMapping("/saml/callback") public String handleSamlCallback() { Saml2AuthenticationToken authentication = (Saml2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); String relayState = authentication.getDetails().getRelayState(); // 后续业务逻辑处理 return "RelayState: " + relayState; } }
说明
Saml2AuthenticationToken.Details是Spring Security SAML2中封装认证请求/响应元数据的对象,其中包含了RelayState、断言ID等信息- 确保你的Spring Security配置正确处理了SAML2认证流程,RelayState会在认证响应阶段被自动传递并绑定到认证token中
内容的提问来源于stack exchange,提问作者SirKM
相关产品推荐
相关产品推荐

