使用 Spring 设置 Azure 客户端凭据流

问题描述

我正在尝试使用 Spring 应用程序访问 Web api(均由我自己拥有)来设置客户端凭据流。我曾尝试遵循 Azure 文档 Microsoft identity platform and the OAuth 2.0 client credentials flowQuickstart: Configure a client application to access a web API,但由于文档不清楚,我遇到了一些问题。在我的设置中,Azure 强制用户登录,然后其他错误消息从那里出现。但是,正如我们所知,客户端凭据应该是机器对机器的授权,所以我不确定为什么会发生这种登录流程。

以下是我的设置。任何反馈都会帮助我开始工作。

环境

OS: Ubuntu 20.10
IDE: Visual Studio Code
Library/Libraries:
com.azure.spring:azure-spring-boot-starter-active-directory:3.5.0
org.springframework.boot:spring-boot-starter-oauth2-client

application.yml

 azure:
  activedirectory:
    tenant-id: {my-web-app-tenant-id}
    client-id: {my-web-app-client-id}
    client-secret: {my-web-app-client-secret}
    authorization-clients:
     web-api:
       scopes:
         - api://example-api/Employees.Read.All
         - api://example-api/Employees.Write.All

Azure 配置

Web-app and web-api registered applications

Web-api scopes and authorized client which matches web-app client

Web-app authentication setup

Web-App permissions,including permission for web-api

解决方法

您当前应该执行服务器到服务器的交互,即没有用户参与。因此,您的服务器应用需要创建一个 appRole,然后将应用角色作为应用权限授予客户端应用

首先需要暴露Azure保护的服务器应用的api,可以按照如下流程进行配置:

Azure 门户>应用注册>公开 API>添加范围>添加客户端应用

enter image description here

然后您需要创建服务器应用程序的 appRole,然后将该角色作为应用程序权限授予客户端应用程序。

enter image description here

接下来,转到客户端应用程序>API 权限>添加权限>我的 API>您的 API 应用程序。

enter image description here

最后,您需要在没有用户登录的情况下使用 client credential flow 获取访问令牌:

enter image description here

解析token:

enter image description here

,

@BillyBolton。

使用 azure-spring-boot-starter-active-directory 时,您的应用程序有多种类型:

  1. 当您的应用程序为 web application 时,将出现登录流程。
  2. 当您的应用程序为 resource server 时,不会出现登录流程。

相关文档:

  1. https://github.com/Azure/azure-sdk-for-java/tree/azure-spring-boot-starter-active-directory_3.6.0/sdk/spring/azure-spring-boot-starter-active-directory#accessing-a-web-application
  2. https://github.com/Azure/azure-sdk-for-java/tree/azure-spring-boot-starter-active-directory_3.6.0/sdk/spring/azure-spring-boot-starter-active-directory#web-application-accessing-resource-servers

相关样本:

  1. https://github.com/Azure-Samples/azure-spring-boot-samples/tree/azure-spring-boot_3.6/aad

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...