Spring Boot资源服务器如何通过B2C访问令牌调用Microsoft Graph API
在Spring Boot资源服务器中使用Azure AD B2C访问令牌调用Microsoft Graph API
核心思路
利用前端传来的用户访问令牌(委托权限令牌)直接调用Microsoft Graph API,关键是确保令牌拥有Graph所需权限,并在Spring Boot中正确初始化Graph客户端发起请求。
步骤1:确认访问令牌的合法性与权限
首先验证前端传来的令牌是否符合要求:
- 用
jwt.ms解析令牌,检查aud(受众)是否为https://graph.microsoft.com,或者你的B2C客户端已配置允许获取Graph权限。 - 查看
scp声明,确认包含调用Graph所需的权限(比如User.Read、User.ReadBasic.All)。 - 确保Azure AD B2C应用注册中,已给Angular客户端添加对应的Microsoft Graph委托权限,且管理员已完成权限同意(若需租户级权限)。
步骤2:引入Microsoft Graph Java SDK依赖
在Spring Boot项目的pom.xml中添加SDK依赖:
<dependency> <groupId>com.microsoft.graph</groupId> <artifactId>microsoft-graph</artifactId> <version>6.3.0</version> <!-- 使用最新稳定版本 --> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.12.0</version> </dependency>
步骤3:初始化Graph客户端并发起调用
从请求头中提取前端传来的Bearer令牌,用它初始化Graph客户端,然后调用API:
import com.microsoft.graph.models.User; import com.microsoft.graph.requests.GraphServiceClient; import java.util.concurrent.CompletableFuture; // 从请求头获取访问令牌 String userToken = request.getHeader("Authorization").replace("Bearer ", ""); // 初始化Graph客户端,直接使用用户令牌做身份验证 GraphServiceClient<?> graphClient = GraphServiceClient.builder() .authenticationProvider(requestAdapter -> { requestAdapter.addHeader("Authorization", "Bearer " + userToken); return CompletableFuture.completedFuture(null); }) .buildClient(); // 调用Graph API获取当前用户信息 try { User currentUser = graphClient.me() .select("id,displayName,mail,userPrincipalName") .buildRequest() .get(); // 处理用户信息,比如返回给前端或业务逻辑使用 System.out.println("用户姓名: " + currentUser.displayName); System.out.println("用户邮箱: " + currentUser.mail); } catch (Exception e) { // 处理异常:令牌过期、权限不足、Graph服务错误等 e.printStackTrace(); }
步骤4:集成Spring Security令牌验证
在资源服务器中先通过Spring Security验证令牌的有效性(签名、过期时间、受众等),再执行Graph调用。典型配置:
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("your-b2c-resource-id"); // 你的资源服务器ID,对应B2C应用注册的ID } @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated(); // 拦截所有请求,确保已认证 } }
关键注意事项
- 不要存储用户令牌,每次请求从前端获取,用完即弃。
- 若调用高权限Graph接口,需确保前端请求令牌时包含对应权限,且管理员已同意。
- 处理Graph API的错误响应,比如401(令牌无效)、403(权限不足),返回友好提示给前端。
内容的提问来源于stack exchange,提问作者Abdi Mohamed
相关产品推荐
相关产品推荐

