Spring Boot 3 RestApi集成Azure AD Bearer Token认证问题排查
Spring Boot 3 + Azure AD Bearer Token 资源访问控制解决方案
核心问题定位
你当前的问题根源在于:Spring Boot 3(对应Spring Security 6)中,RestAPI作为资源服务器需要使用oauth2-resource-server模块处理Bearer Token认证,而非仅依赖oauth2-client。oauth2-client主要用于实现授权码/密码等客户端登录流程,默认会触发表单登录跳转;而资源服务器需要直接验证请求头中的Bearer Token,不需要跳转登录页面。
具体解决方案
1. 调整依赖
确保pom.xml(或build.gradle)中添加资源服务器核心依赖:
<!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
(若已添加oauth2-client可保留,但无需依赖它完成Token验证)
2. 配置Azure AD参数
在application.yml中配置租户与应用的核心信息:
spring: security: oauth2: resourceserver: jwt: issuer-uri: https://login.microsoftonline.com/{你的租户ID}/v2.0 audience: {Azure门户中注册的应用客户端ID}
issuer-uri:可从Azure门户应用的「终结点」页面获取,是租户的OIDC发行者地址。audience:必须与你获取的Token中aud字段值一致(v2.0端点生成的Token默认aud为应用客户端ID)。
3. Spring Security 6 配置类
Spring Security 6弃用了WebSecurityConfigurerAdapter,改用SecurityFilterChain做组件式配置,示例如下:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // RestAPI场景关闭CSRF防护 .csrf(csrf -> csrf.disable()) // 所有请求需认证 .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) // 彻底禁用表单登录,避免跳转登录页 .formLogin(form -> form.disable()) // 开启OAuth2资源服务器的Bearer Token验证逻辑 .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())); return http.build(); } }
常见排查点
- Token合法性校验:用jwt.io解析Token,检查
iss是否匹配配置的issuer-uri、aud是否对应audience,同时确认Token未过期。 - 请求头格式:确保请求头
Authorization的值为Bearer {Token},注意Bearer后有空格,无拼写错误。 - 依赖版本一致性:检查所有Spring Boot相关依赖版本统一,Spring Boot 3.x必须对应Spring Security 6.x,避免版本冲突。
- 权限控制扩展:若需基于角色/权限限制访问,可在Azure AD中配置应用角色,然后在配置类中添加规则(例如
auth.anyRequest().hasAuthority("SCOPE_你的权限标识"))。
与Spring Boot 2.x的区别
Spring Boot 2.1.3中自定义过滤器的方式在新版本已无需使用,Spring Security 6原生集成了Azure AD JWT Token的验证逻辑,通过上述配置即可实现认证,无需再自定义AzureAuthFilter和AzureUserPrincipalManager。
内容的提问来源于stack exchange,提问作者Peter F
相关产品推荐
相关产品推荐

