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

如何在SpringBoot API中用spring-boot-starter-oauth2-client验证解码Azure AD JWT令牌

用spring-boot-starter-oauth2-client验证Azure AD idToken并提取用户信息

1. 添加依赖

在pom.xml(Maven)中引入必要依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
</dependencies>

注:虽然你指定用spring-boot-starter-oauth2-client,但作为API服务,结合oauth2-resource-server能更直接实现JWT令牌验证逻辑。

2. 配置Azure AD参数

在application.yml中填入Azure AD的租户、客户端及令牌验证端点信息:

spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            client-id: "你的API应用在Azure AD中的Client ID"
            client-secret: "你的API应用在Azure AD中的Client Secret"
            scope: openid, profile, email
        provider:
          azure:
            issuer-uri: "https://login.microsoftonline.com/{你的租户ID}/v2.0"
            jwk-set-uri: "https://login.microsoftonline.com/{你的租户ID}/discovery/v2.0/keys"
      resource-server:
        jwt:
          issuer-uri: "https://login.microsoftonline.com/{你的租户ID}/v2.0"

配置中的issuer-uri和jwk-set-uri是Azure AD v2.0标准端点,Spring会自动通过这些地址获取令牌验证所需的公钥,无需手动配置。

3. 配置Spring Security规则

创建SecurityConfig类,设置API的访问权限及令牌验证逻辑:

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;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(new AzureAdJwtAuthenticationConverter()) // 可选:自定义令牌转换逻辑
                )
            );
        return http.build();
    }
}

4. 提取用户信息

在API控制器中,直接通过@AuthenticationPrincipal注解获取JWT令牌,从中提取用户信息:

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/api/user/info")
    public UserInfo getUserInfo(@AuthenticationPrincipal Jwt jwt) {
        // 从JWT的claims中提取核心用户信息
        String userId = jwt.getClaim("sub");
        String userName = jwt.getClaim("name");
        String email = jwt.getClaim("email");
        String tenantId = jwt.getClaim("tid");

        return new UserInfo(userId, userName, email, tenantId);
    }

    // 自定义用户信息DTO,用于返回结果
    static class UserInfo {
        private String userId;
        private String userName;
        private String email;
        private String tenantId;

        // 构造器、getter、setter省略
    }
}

如果需要将JWT信息转换为自定义的UserDetails对象以适配后续应用管理逻辑,可以实现JwtAuthenticationConverter接口完成自定义转换。

自动验证逻辑说明

Spring Security会自动完成以下idToken验证步骤,无需手动编码:

  • 通过JWKS端点获取的公钥验证令牌签名有效性
  • 检查令牌是否在有效期内(验证exp和nbf字段)
  • 确认令牌受众(aud)与API的client-id匹配
  • 验证令牌颁发者(iss)与配置的issuer-uri一致

若验证失败,Spring Security会直接返回401 Unauthorized响应。

调试建议

  • 用Azure官方的令牌解析工具查看idToken的结构和字段,确认claims内容符合预期
  • 开启Spring Security的DEBUG日志(配置logging.level.org.springframework.security=DEBUG),查看令牌验证的详细流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:58:13