Spring Boot服务无用户登录调用Microsoft Graph时遇空指针异常
解决Spring Boot服务身份调用Microsoft Graph时的NullPointerException问题
你遇到的错误Cannot invoke "org.springframework.security.oauth2.client.OAuth2AuthorizedClient.getAccessToken()" because "this.graphAuthorizedClient" is null,根源有两个核心问题,对应解决方案如下:
1. 修正控制器代码变量名错误
你的控制器方法参数是OAuth2AuthorizedClient graph,但构造GraphAuthenticationProvider时传入了未定义的graphAuthorizedClient变量,导致构造器接收的参数为null,最终触发空指针异常。
修正后的控制器代码:
@GetMapping("call-graph") public String callGraph(@RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient graph) { GraphServiceClient client = GraphServiceClient.builder() .authenticationProvider(new GraphAuthenticationProvider(graph)) .buildClient(); return callMicrosoftGraphMeEndpoint(client); }
2. 完善客户端凭证模式配置
你需要的是服务身份调用(无需用户登录),对应OAuth2的客户端凭证流,但当前配置未明确指定授权类型,Spring Cloud Azure可能默认使用授权码流,无法正确获取服务身份的令牌。
更新后的YAML配置:
spring: cloud: azure: active-directory: enabled: true profile: tenant-id: <tenant-ID-registered-by-application> credential: client-id: <web-API-A-client-ID> client-secret: <web-API-A-client-secret> authorization-clients: graph: authorization-grant-type: client_credentials scopes: - https://graph.microsoft.com/.default
注意:客户端凭证模式下,Graph的scope必须使用
https://graph.microsoft.com/.default,这会包含你在Azure AD中为应用注册的所有应用权限(而非委托权限)。同时要确保在Azure AD应用注册的「API权限」页面:
- 添加Microsoft Graph的应用权限(如
User.Read.All,User.Read是委托权限,客户端凭证模式无法使用)- 点击「授予管理员同意」完成权限生效
内容的提问来源于stack exchange,提问作者user1555190
相关产品推荐
相关产品推荐

