我已在 Azure API 管理服务中设置了一个 API,我想使用 OAUth2 来保护该 API。 后端服务实际上是一个本地重置端点,在 azure 和我们的组织之间有 ExpressRoute 连接。
为了启用 OAuth,我按照以下在线教程进行操作:
为后端服务创建一个“后端”应用程序注册,并使用默认值。
为客户端应用程序创建一个“客户端”应用程序注册,并使用默认值
我创建一个 API 和操作,并使用入站 validate-jwt 和模拟响应策略配置 API(模拟响应,因为我的本地后端服务尚未完成)。
使用 Postman,我可以从端点检索令牌,但是当我使用该令牌调用 api 时,我只是得到一个无效或丢失的令牌
诚然,我不清楚这两个应用程序注册如何协同工作,以及各自扮演什么角色,但我猜测问题可能出在我的策略中,或者在后端注册中,至少我可以做到获得令牌?
这是我的API政策:
<policies>
<inbound>
<base />
<!-- Look for authorization header bearer token and validate the token against the identity provider -->
<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.microsoftonline.com/{tenant-id}/v2.0/.well-known/openid-configuration" />
<required-claims>
<claim name="aud">
<value>api://bcaa2716-xxxx-xxxx-xxxx-09eca63145d3</value>
</claim>
</required-claims>
</validate-jwt>
<mock-response status-code="200" content-type="application/json" />
</inbound>
<!-- Control if and how the requests are forwarded to services -->
<backend>
<base />
</backend>
<!-- Customize the responses -->
<outbound>
<base />
</outbound>
<!-- Handle exceptions and customize error responses -->
<on-error>
<base />
</on-error>
</policies>
令牌请求:
POST https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 95
client_id=1ee63a96-xxxx-xxxx-xxxx-d33a13cafdcc&scope=api://bcaa2716-xxxx-xxxx-xxxx-09eca63145d3&client_secret={secret}&grant_type=client_credentials
令牌响应:
HTTP/1.1 200 OK
...
Content-Length: 1369
{"token_type":"Bearer","expires_in":3599,"ext_expires_in":3599,"access_token":"eyJ0eXAiOiJK...XwkpxaKpw"}
API请求
POST https://xxxxx-apim.azure-api.net/testoauth2/test HTTP/1.1
Ocp-Apim-Subscription-Key: 24b2xxxxxxxxxx3c192a03ca
Authorization: Bearer eyJ0eXAiOiJK...XwkpxaKpw
Content-Length: 0
API响应
HTTP/1.1 401 Unauthorized
Content-Length: 85
Content-Type: application/json
Request-Context: appId=cid-v1:af45326e-7707-4d17-af03-c890faa72200
Date: Fri, 09 Aug 2024 18:24:01 GMT
{ "statusCode": 401, "message": "Unauthorized. Access token is missing or invalid." }
您应在资源服务器 (Azure APIM) 中配置的受众是其客户端 ID。您可以将其视为代表一个或多个 API 的逻辑标识符。
bcaa2716-xxxx-xxxx-xxxx-09eca63145d3
为了获得可行的解决方案,我最初会使用最少的配置,只是为了使令牌签名验证正常工作。还要确保您在服务器端错误日志记录方面做了一些工作,以便您可以诊断故障。
工作后,您应该对所有这些添加检查。您可以使用任何在线 JWT 查看器与访问令牌中的值进行比较:
Issuer = https://login.microsoftonline.com/{tenant-id}/v2.0
Audience = bcaa2716-xxxx-xxxx-xxxx-09eca63145d3
Scope = api://bcaa2716-xxxx-xxxx-xxxx-09eca63145d3/.default
有关详细信息,请参阅Microsoft 文档。例如,在某些特殊元素中可以表达
<issuers>
和 <audience>
,而范围检查则在所需的权利要求下表达。