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

非Spring Boot环境下Spring Security SAML无法获取用户信息

问题:SAML集成后Saml2AuthenticatedPrincipal始终为null

在基于Spring Framework 5.3.24、Spring Security 5.6.10、OpenSAML 3.4.6的旧项目中集成SAML,完成开发后,在Okta端登录成功,但控制器中通过@AuthenticationPrincipal获取的Saml2AuthenticatedPrincipal一直是null。

相关代码如下:

1. SAML配置类

@Configuration
public class SAMLSecurityConfig {
    private static final String URL_METADATA = "https://auth-dev.mycompany.com/app/id/sso/saml/metadata";

    @Bean("samlRegistration")
    public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
        RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(URL_METADATA)
                .registrationId("id")
                .build();

        return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
    }
}

2. Web安全配置类

@EnableWebSecurity
public class WebSecurity {
    
    @Configuration
    @Order(2)
    public static class SAMLSecurityFilter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.saml2Login(Customizer.withDefaults())
                    .antMatcher("/login/assertion")
                    .authorizeRequests()
                    .anyRequest()
                    .authenticated();
        }
    }
}

3. 登录控制器

@Controller("loginController")
public class BoCRLoginController {


    @RequestMapping(value = "/login/assertion", method = {RequestMethod.POST},
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> assertLoginData(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
        System.out.println(principal);  // 此处输出null
        return new ResponseEntity<>(HttpStatus.OK);
    }

}

原因分析与解决办法

1. 安全配置的顺序和路径匹配逻辑错误

你给SAMLSecurityFilter设置了@Order(2),如果项目里还有其他优先级更高(Order数值更小)的安全配置,会先拦截/login/assertion请求,导致SAML2过滤器链根本没处理这个请求,认证信息自然无法注入。

另外,HttpSecurity的配置顺序也错了,应该先指定路径匹配,再配置SAML2登录:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .antMatcher("/login/assertion") // 先声明要匹配的路径
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
            .saml2Login(Customizer.withDefaults()); // 再配置SAML2登录逻辑
}

2. 断言消费端点未正确配置

Spring Security SAML2默认的断言消费端点是/login/saml2/sso/{registrationId},但你自定义了/login/assertion作为接收端点,却没在RelyingPartyRegistration里配置这个URL,导致Okta发送的断言没被SAML2过滤器处理,无法生成认证信息。

需要在注册配置里显式指定断言消费地址:

@Bean("samlRegistration")
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
    RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(URL_METADATA)
            .registrationId("id")
            // 替换成你的应用实际域名
            .assertionConsumerServiceLocation("https://your-app-domain/login/assertion")
            .build();

    return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
}

同时要保证Okta后台配置的断言消费URL和这个地址完全一致,包括协议、域名、路径。

3. 控制器直接处理了断言请求

Spring Security的SAML2过滤器会自动解析POST过来的断言数据,完成认证后才会生成Saml2AuthenticatedPrincipal。但你直接在控制器里消费了application/x-www-form-urlencoded类型的请求,跳过了过滤器链的处理,自然拿不到认证信息。

建议修改控制器,让它处理认证成功后的跳转逻辑,而不是直接接收断言:

@Controller
public class BoCRLoginController {

    @GetMapping("/login/success")
    public ResponseEntity<String> loginSuccess(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
        // 这里可以正常获取用户属性
        System.out.println(principal.getAttributes());
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

然后在SAML2登录配置里指定成功跳转路径:

httpSecurity
        .antMatcher("/login/saml2/sso/id")
        .authorizeRequests()
            .anyRequest().authenticated()
        .and()
        .saml2Login(saml2 -> saml2
                .successHandler((request, response, authentication) -> {
                    response.sendRedirect("/login/success");
                })
        );

4. 依赖版本可能存在冲突

Spring Security 5.6.x和OpenSAML 3.4.6的组合需要确保依赖传递正确,检查项目依赖树,避免出现不同版本的OpenSAML依赖。可以在pom.xml里显式锁定版本:

<dependency>
    <groupId>org.opensaml</groupId>
    <artifactId>opensaml-core</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>org.opensaml</groupId>
    <artifactId>opensaml-saml-api</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>org.opensaml</groupId>
    <artifactId>opensaml-saml-impl</artifactId>
    <version>3.4.6</version>
</dependency>

内容的提问来源于stack exchange,提问作者Edgar Arizmendi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:25:21