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

Spring Security:SecurityFilterChain中应用SecurityConfigurer及自定义配置

问题:Spring Boot中结合Azure AD资源服务器配置与CSRF禁用的Lambda格式实现

我需要在Spring Boot项目中同时实现以下三点:

  • 禁用CSRF保护(应用不通过浏览器访问,解决Spring Security对非GET端点的默认CSRF限制)
  • 应用Spring Cloud Azure 5.X版本的SecurityConfigurer,实现Azure AD资源服务器的权限校验
  • 使用Spring Security新的Lambda配置格式(避免使用已弃用的and()方法)

原配置代码

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .apply(AadResourceServerHttpSecurityConfigurer.aadResourceServer())
            .and()
        .authorizeHttpRequests(authorizeHttpRequests -> 
            authorizeHttpRequests
                .anyRequest()
                .authenticated())
        .csrf(csrf -> csrf.disable());
    return http.build();
}

遇到的问题

上述配置已经能通过@PreAuthorize注解完成Azure应用/用户的权限校验,但CSRF保护并未成功禁用——用Postman调用非GET端点时会返回401错误。想请教:在应用SecurityConfigurer后如何进行后续自定义配置?是否可以同时使用新的Lambda格式?


临时解决方案(场景特定)

在这个Azure AD资源服务器的场景中,微软提供的配置器已经为OAuth2授权的请求自动禁用了CSRF保护,因此全局禁用CSRF其实没有必要,因为所有非GET端点都应该通过OAuth2授权访问。我之前出现问题是因为实验阶段暂时没添加OAuth2授权。

如果有人在实现该微软配置器时遇到CSRF相关问题:无需自定义SecurityFilterChain,只需确保所有非GET端点都通过OAuth2授权即可。


最终解决方案(满足所有需求)

关键在于不再使用apply()方法来应用安全配置器,而是改用with()方法,这样就能完美结合Lambda格式完成所有配置。正确代码如下:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .with(AadResourceServerHttpSecurityConfigurer.aadResourceServer(), Customizer.withDefaults())
        .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
        .csrf(csrf -> csrf.disable());
    return http.build();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:01:12