结合 Azure Active Directory 和 API 管理使用 OAuth 2.0 保护 APIProtect an API by using OAuth 2.0 with Azure Active Directory and API Management

本指南介绍如何结合 Azure Active Directory (Azure AD) 使用 OAuth 2.0 协议配置 Azure API 管理实例,以保护 API。This guide shows you how to configure your Azure API Management instance to protect an API, by using the OAuth 2.0 protocol with Azure Active Directory (Azure AD).

备注

此功能可在“开发人员”、“基本”、“标准”和“高级”层中使用 。This feature is available in Developer, Basic, Standard, and Premium tiers of API Management.

先决条件Prerequisites

若要执行本文中的步骤,必须提供:To follow the steps in this article, you must have:

  • API 管理实例An API Management instance
  • 使用 API 管理实例发布的 APIAn API being published that uses the API Management instance
  • Azure AD 租户An Azure AD tenant

概述Overview

以下是简要的步骤概述:The following is a quick overview of the steps:

  1. 在 Azure AD 中注册一个应用程序(后端应用)用于表示 API。Register an application (backend-app) in Azure AD to represent the API.
  2. 在 Azure AD 中注册另一个应用程序(客户端应用),用于表示需要调用 API 的客户端应用程序。Register another application (client-app) in Azure AD to represent a client application that needs to call the API.
  3. 在 Azure AD 中授予权限,使客户端应用能够调用后端应用。In Azure AD, grant permissions to allow the client-app to call the backend-app.
  4. 将开发人员控制台配置为使用 OAuth 2.0 用户授权调用 API。Configure the Developer Console to call the API using OAuth 2.0 user authorization.
  5. 添加 validate-jwt 策略以验证每个传入请求的 OAuth 令牌。Add the validate-jwt policy to validate the OAuth token for every incoming request.

在 Azure AD 中注册一个应用程序用于表示 APIRegister an application in Azure AD to represent the API

若要使用 Azure AD 保护 API,请首先在 Azure AD 中注册一个表示该 API 的应用程序。To protect an API with Azure AD, first register an application in Azure AD that represents the API.

  1. 转到 Azure 门户来注册应用程序。Go to the Azure portal to register your application. 搜索并选择“应用注册”。Search for and select APP registrations.

  2. 选择“新注册”。Select New registration.

  3. 出现“注册应用程序”页后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:

    • 在“名称”部分中,输入一个将显示给应用用户的有意义的应用程序名称,例如 backend-appIn the Name section, enter a meaningful application name that will be displayed to users of the app, such as backend-app.
    • 在“支持的帐户类型”部分,选择适合你的方案的选项。In the Supported account types section, select an option that suits your scenario.
  4. 将“重定向 URI”部分留空。Leave the Redirect URI section empty.

  5. 选择“注册”以创建应用程序。Select Register to create the application.

  6. 在应用的“概述”页上,找到“应用程序(客户端) ID”值,并记下该值以供后续使用 。On the app Overview page, find the Application (client) ID value and record it for later.

  7. 选择“公开 API”,并将“应用程序 ID URI”设为默认值。Select Expose an API and set the Application ID URI with the default value. 记下此值以备将来使用。Record this value for later.

  8. 选择“添加作用域”按钮以显示“添加作用域”页面。Select the Add a scope button to display the Add a scope page. 然后创建该 API 支持的一个新作用域(例如 Files.Read)。Then create a new scope that's supported by the API (for example, Files.Read).

  9. 选择“添加作用域”按钮以创建作用域。Select the Add scope button to create the scope. 重复此步骤以添加 API 支持的所有范围。Repeat this step to add all scopes supported by your API.

  10. 创建作用域后,请记下它们,以便在后续步骤中使用。When the scopes are created, make a note of them for use in a subsequent step.

在 Azure AD 中注册另一个应用程序用于表示客户端应用程序Register another application in Azure AD to represent a client application

每个调用该 API 的客户端应用程序都需要在 Azure AD 中注册为应用程序。Every client application that calls the API needs to be registered as an application in Azure AD. 在本示例中,客户端应用程序是 API 管理开发人员门户中的“开发人员控制台”。In this example, the client application is the Developer Console in the API Management developer portal.

在 Azure AD 中注册另一个应用程序,用于表示开发人员控制台:To register another application in Azure AD to represent the Developer Console:

  1. 转到 Azure 门户来注册应用程序。Go to the Azure portal to register your application.

  2. 搜索并选择“应用注册”。Search for and select APP registrations.

  3. 选择“新注册”。Select New registration.

  4. 出现“注册应用程序”页后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:

    • 在“名称”部分中,输入一个将显示给应用用户的有意义的应用程序名称,例如 client-appIn the Name section, enter a meaningful application name that will be displayed to users of the app, such as client-app.
    • 在“支持的帐户类型”部分中,选择“任何组织目录(任何 Azure AD 目录 - 多租户)中的帐户”。 In the Supported account types section, select Accounts in any organizational directory (Any Azure AD directory - Multitenant).
  5. 在“重定向 URI”部分中,选择 Web 并将 URL 字段暂时保留为空。In the Redirect URI section, select Web and leave the URL field empty for now.

  6. 选择“注册”以创建应用程序。Select Register to create the application.

  7. 在应用的“概述”页上,找到“应用程序(客户端) ID”值,并记下该值以供后续使用 。On the app Overview page, find the Application (client) ID value and record it for later.

  8. 为此应用程序创建客户端密码,以在后续步骤中使用。Create a client secret for this application to use in a subsequent step.

    1. 从客户端应用的页面列表中,选择“证书和机密”,然后选择“新建客户端密码”。From the list of pages for your client app, select Certificates & secrets, and select New client secret.

    2. 在“添加客户端密码”下,提供说明Under Add a client secret, provide a Description. 选择密钥过期时间,然后选择“添加”。Choose when the key should expire, and select Add.

创建机密后,请记下密钥值,以便在后续步骤中使用。When the secret is created, note the key value for use in a subsequent step.

在 Azure AD 中授予权限Grant permissions in Azure AD

注册了用于表示 API 和开发人员控制台的两个应用程序之后,请授予权限以允许客户端应用调用后端应用。Now that you have registered two applications to represent the API and the Developer Console, grant permissions to allow the client-app to call the backend-app.

  1. 转到 Azure 门户来向客户端应用程序授予权限。Go to the Azure portal to grant permissions to your client application. 搜索并选择“应用注册”。Search for and select APP registrations.

  2. 选择你的客户端应用程序。Choose your client app. 然后,在应用的页面列表中,选择“API 权限”。Then in the list of pages for the app, select API permissions.

  3. 选择“添加权限”。Select Add a Permission.

  4. 在“选择 API”下,选择“我的 API”,然后找到并选择你的 backend-app。Under Select an API, select My APIs, and then find and select your backend-app.

  5. 在“委托的权限”下,选择对 backend-app 的适当权限,然后选择“添加权限”。 Under Delegated Permissions, select the appropriate permissions to your backend-app, then select Add permissions.

  6. (可选)在“API 权限”页上,选择“授予对 <your-tenant-name> 的管理员许可”,为此目录中的所有用户授予许可。 Optionally, on the API permissions page, select Grant admin consent for <your-tenant-name> to grant consent on behalf of all users in this directory.

在开发人员门户中启用 OAuth 2.0 用户授权Enable OAuth 2.0 user authorization in the Developer Console

此时,我们已在 Azure AD 中创建应用程序,并已授予适当的权限来让客户端应用调用后端应用。At this point, you have created your applications in Azure AD, and have granted proper permissions to allow the client-app to call the backend-app.

在本示例中,开发人员控制台是 client-app。In this example, the Developer Console is the client-app. 以下步骤说明如何在开发人员门户中启用 OAuth 2.0 用户授权The following steps describe how to enable OAuth 2.0 user authorization in the Developer Console.

  1. 在 Azure 门户中,浏览找到你的 API 管理实例。In Azure portal, browse to your API Management instance.

  2. 选择“OAuth 2.0” > “添加”。 Select OAuth 2.0 > Add.

  3. 提供“显示名称”和“说明”。 Provide a Display name and Description.

  4. 对于“客户端注册页 URL”,请输入占位符值,如 http://localhostFor the Client registration page URL, enter a placeholder value, such as http://localhost. “客户端注册页 URL”指向供用户针对 OAuth 2.0 提供程序创建和配置其自己的帐户的页面。The Client registration page URL points to a page that users can use to create and configure their own accounts for OAuth 2.0 providers that support this. 在此示例中,用户不创建和配置自己的帐户,因此使用了占位符。In this example, users do not create and configure their own accounts, so you use a placeholder instead.

  5. 选择“授权代码”作为“授权类型”。 For Authorization grant types, select Authorization code.

  6. 指定“授权终结点 URL”和“令牌终结点 URL”。Specify the Authorization endpoint URL and Token endpoint URL. 可以从 Azure AD 租户中的“终结点”页检索这些值。Retrieve these values from the Endpoints page in your Azure AD tenant. 再次浏览到“应用注册”页,并选择“终结点”。 Browse to the App registrations page again, and select Endpoints.

  7. 复制“OAuth 2.0 授权终结点”,并将其粘贴到“授权终结点 URL”文本框。Copy the OAuth 2.0 Authorization Endpoint, and paste it into the Authorization endpoint URL text box. 选择“授权”请求方法下的“POST”。Select POST under Authorization request method.

  8. 复制“OAuth 2.0 令牌终结点”,并将其粘贴到“令牌终结点 URL”文本框。Copy the OAuth 2.0 Token Endpoint, and paste it into the Token endpoint URL text box.

    重要

    使用“v1”或“v2”终结点 。Use either v1 or v2 endpoints. 但是,根据所选的版本,以下步骤将有所不同。However, depending on which version you choose, the below step will be different. 我们建议使用 v2 终结点。We recommend using v2 endpoints.

  9. 如果使用 v1 终结点,请添加名为 resource 的主体参数。If you use v1 endpoints, add a body parameter named resource. 使用后端应用的“应用程序 ID”作为此参数的值。For the value of this parameter, use Application ID of the back-end app.

  10. 如果使用 v2 终结点,请在“默认范围”字段中使用为后端应用创建的范围。If you use v2 endpoints, use the scope you created for the backend-app in the Default scope field. 另外,确保在应用程序清单中将 accessTokenAcceptedVersion 属性的值设置为 2Also, make sure to set the value for the accessTokenAcceptedVersion property to 2 in your application manifest.

  11. 接下来,指定客户端凭据。Next, specify the client credentials. 这些是 client-app 的凭据。These are the credentials for the client-app.

  12. 对于“客户端 ID”,请使用客户端应用的“应用程序 ID”。 For Client ID, use the Application ID of the client-app.

  13. 对于“客户端机密”,请使用前面为 client-app 创建的密钥。For Client secret, use the key you created for the client-app earlier.

  14. 紧接在客户端机密的后面,是授权代码授权类型的 redirect_urlImmediately following the client secret is the redirect_url for the authorization code grant type. 记下此 URL。Make a note of this URL.

  15. 选择“创建” 。Select Create.

  16. 返回到 Azure Active Directory 中的客户端应用注册,并选择“身份验证”。Go back to your client-app registration in Azure Active Directory and select Authentication.

  17. 在“平台配置”下,单击“添加平台”,然后选择“Web”作为类型,将“redirect_url”粘贴在“重定向 URI”下,然后单击“配置”按钮进行保存。Under Platform configurations click on Add a platform, and select the type as Web, paste the redirect_url under Redirect URI, and then click on Configure button to save.

配置 OAuth 2.0 授权服务器后,开发人员控制台可从 Azure AD 获取访问令牌。Now that you have configured an OAuth 2.0 authorization server, the Developer Console can obtain access tokens from Azure AD.

下一步是为 API 启用 OAuth 2.0 用户授权。The next step is to enable OAuth 2.0 user authorization for your API. 这使得开发人员控制台知道在调用 API 之前,需要代表用户获取访问令牌。This enables the Developer Console to know that it needs to obtain an access token on behalf of the user, before making calls to your API.

  1. 浏览到 API 管理实例,并转到“API”。Browse to your API Management instance, and go to APIs.

  2. 选择要保护的 API。Select the API you want to protect. 例如,Echo APIFor example, Echo API.

  3. 转到“设置”。Go to Settings.

  4. 在“安全性”下,选择“OAuth 2.0”并选择前面配置的 OAuth 2.0 服务器。 Under Security, choose OAuth 2.0, and select the OAuth 2.0 server you configured earlier.

  5. 选择“保存” 。Select Save.

从开发人员门户成功调用 APISuccessfully call the API from the developer portal

备注

本部分不适用于“消耗”层,该层不支持开发人员门户。This section does not apply to the Consumption tier, which does not support the developer portal.

在 API 中启用 OAuth 2.0 用户授权后,开发人员控制台在调用 API 之前,将会代表用户获取访问令牌。Now that the OAuth 2.0 user authorization is enabled on your API, the Developer Console will obtain an access token on behalf of the user, before calling the API.

  1. 在开发人员门户中浏览到 API 下的任一操作,并选择“试用”。Browse to any operation under the API in the developer portal, and select Try it. 随后会转到开发人员控制台。This brings you to the Developer Console.

  2. 可以看到,“授权”部分出现了一个与刚刚添加的授权服务器对应的新项。Note a new item in the Authorization section, corresponding to the authorization server you just added.

  3. 从授权下拉列表中选择“授权代码”。系统会提示登录到 Azure AD 租户。Select Authorization code from the authorization drop-down list, and you are prompted to sign in to the Azure AD tenant. 如果已使用帐户登录,则可能不会出现提示。If you are already signed in with the account, you might not be prompted.

  4. 成功登录后,会将一个 Authorization 标头添加到请求,该标头包含从 Azure AD 获取的访问令牌。After successful sign-in, an Authorization header is added to the request, with an access token from Azure AD. 下面是一个采用 Base64 编码的示例令牌:The following is a sample token (Base64 encoded):

    Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IlNTUWRoSTFjS3ZoUUVEU0p4RTJnR1lzNDBRMCIsImtpZCI6IlNTUWRoSTFjS3ZoUUVEU0p4RTJnR1lzNDBRMCJ9.eyJhdWQiOiIxYzg2ZWVmNC1jMjZkLTRiNGUtODEzNy0wYjBiZTEyM2NhMGMiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC80NDc4ODkyMC05Yjk3LTRmOGItODIwYS0yMTFiMTMzZDk1MzgvIiwiaWF0IjoxNTIxMTUyNjMzLCJuYmYiOjE1MjExNTI2MzMsImV4cCI6MTUyMTE1NjUzMywiYWNyIjoiMSIsImFpbyI6IkFWUUFxLzhHQUFBQUptVzkzTFd6dVArc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m0bTMefoyX8oqfMEA2ziKjwvBFrOjO0uK4rJLgLYH4qvkR0bdF9etdstqKMo5gecarWHNzWi_tghQu9aE3Z3EZdYNI_ZGM-Bbe3pkCfvEOyA
    
  5. 选择“发送”以成功调用 API。Select Send to call the API successfully.

配置 JWT 验证策略,对请求进行预授权Configure a JWT validation policy to pre-authorize requests

此时,当用户尝试从开发人员控制台发出调用时,系统会提示其登录。At this point, when a user tries to make a call from the Developer Console, the user is prompted to sign in. 开发人员控制台将代表用户获取访问令牌,并在对 API 发出的请求中包含该令牌。The Developer Console obtains an access token on behalf of the user, and includes the token in the request made to the API.

但是,如果有人调用我们的 API 但未提供令牌或者提供无效的令牌,会发生什么情况?However, what if someone calls your API without a token or with an invalid token? 例如,如果在不使用 Authorization 标头的情况下尝试调用 API,调用仍将继续。For example, try to call the API without the Authorization header, the call will still go through. 原因是 API 管理暂时不会验证访问令牌。The reason is that API Management does not validate the access token at this point. 它只是将 Authorization 标头传递给后端 API。It simply passes the Authorization header to the back-end API.

使用验证 JWT 策略通过验证每个传入请求的访问令牌,对 API 管理中的请求进行预授权。Use the Validate JWT policy to pre-authorize requests in API Management, by validating the access tokens of each incoming request. 如果某个请求没有有效的令牌,API 管理会阻止该请求。If a request does not have a valid token, API Management blocks it. 例如,在 Echo API<inbound> 策略部分中添加以下策略。For example, add the following policy to the <inbound> policy section of the Echo API. 它会检查访问令牌中的受众声明,如果令牌无效,则会返回一条错误消息。It checks the audience claim in an access token, and returns an error message if the token is not valid. 有关如何配置策略的信息,请参阅设置或编辑策略For information on how to configure policies, see Set or edit policies.

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.partner.microsoftonline.cn/{aad-tenant}/.well-known/openid-configuration" />
    <required-claims>
        <claim name="aud">
            <value>{Application ID of backend-app}</value>
        </claim>
    </required-claims>
</validate-jwt>

备注

openid-config URL 对应于 v1 终结点。This openid-config URL corresponds to the v1 endpoint. 对于 v2 openid-config 终结点,请使用以下 URL:For the v2 openid-configendpoint, use the following URL:

https://login.partner.microsoftonline.cn/common/v2.0/.well-known/openid-configurationhttps://login.partner.microsoftonline.cn/common/v2.0/.well-known/openid-configuration.

生成应用程序来调用 APIBuild an application to call the API

在本指南中,我们使用了 API 管理中的开发者控制台作为示例客户端应用程序来调用由 OAuth 2.0 保护的 Echo APIIn this guide, you used the Developer Console in API Management as the sample client application to call the Echo API protected by OAuth 2.0. 若要详细了解如何生成应用程序并实现 OAuth 2.0,请参阅 Azure Active Directory 代码示例To learn more about how to build an application and implement OAuth 2.0, see Azure Active Directory code samples.

后续步骤Next steps