Azure AD认证下Angular应用调用Spring Boot资源服务后访问另一资源服务的实现问题
问题解答
你的判断正确,该场景属于OAuth2标准的On-Behalf-Of(代表用户,简称OBO)流程,资源服务器A确实需要同时配置为资源服务器和OAuth2客户端。
构造访问资源服务器B的请求流程
前置配置(Azure AD侧)
- 为资源服务器A的应用注册添加资源服务器B暴露的委托类型API权限,完成权限授予操作。
- 确保资源服务器A自身的API已暴露,且Angular前端已配置正确的访问scope。
Spring Boot配置(资源服务器A侧)
在application.yml中添加如下配置:
spring: cloud: azure: active-directory: client-id: 资源服务器A的客户端ID client-secret: 资源服务器A的客户端密钥 app-id-uri: 资源服务器A的应用ID URI authorization-clients: # 自定义下游资源服务标识 resource-server-b: scopes: # 填写资源服务器B暴露的完整API scope,例如api://xxxx-xxxx/access.b - 资源服务器B的API scope
代码实现请求调用
注入OAuth2AuthorizedClientManager完成令牌换发和请求构造,示例代码如下:
@RestController public class ServerAController { private final RestTemplate restTemplate = new RestTemplate(); private final OAuth2AuthorizedClientManager authorizedClientManager; public ServerAController(OAuth2AuthorizedClientManager authorizedClientManager) { this.authorizedClientManager = authorizedClientManager; } @GetMapping("/call-b-api") public String callResourceB(Authentication authentication) { // 构造OBO授权请求,registrationId对应yml中配置的resource-server-b OAuth2AuthorizeRequest request = OAuth2AuthorizeRequest.withClientRegistrationId("resource-server-b") .principal(authentication) .build(); // 自动完成OBO流令牌换发,获取访问资源服务器B的令牌 OAuth2AuthorizedClient client = authorizedClientManager.authorize(request); String tokenForB = client.getAccessToken().getTokenValue(); // 构造携带令牌的请求访问资源服务器B HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(tokenForB); HttpEntity<Void> httpEntity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( "http://资源服务器B的接口地址", HttpMethod.GET, httpEntity, String.class ); return response.getBody(); } }
资源服务器B仅需按照标准Azure AD资源服务器流程配置,验证请求令牌合法性即可,无需额外适配OBO流。
CallGraph方法的作用
callGraph是Azure AD starter封装的便利工具,专门用于调用Microsoft Graph API。该方法已经预配置了Graph API的访问scope、请求模板和令牌换发逻辑,开发者无需手动配置Graph相关的客户端参数、编写令牌获取和请求构造代码,直接调用方法即可访问Graph接口。如果业务不需要调用Microsoft Graph API,可以完全不使用该方法,通过前文的自定义方式调用其他自研资源服务器即可。
内容的提问来源于stack exchange,提问作者Orzelke
相关产品推荐
相关产品推荐

