上游客户端为用户登录,并向代理发送访问令牌。 在使用用户声明或执行 On-Behalf-Of (OBO) 交换之前,代理会先将该令牌传递给 sidecar 进行验证。
边车不提供登录用户界面。 在上游 Web、桌面或移动客户端中使用 MSAL。
Prerequisites
- 完成配置 Auth SDK sidecar,包括代理的注册和凭据。
- 一个上游客户端,用于登录用户并请求代理公开作用域的令牌。
- 完成配置委派权限和授予上游客户端访问权限。 这些注册和 Microsoft Graph 同意步骤也适用于 sidecar;请勿使用该文章中的 ASP.NET Core 代码。
配置受众
注册代理 API 公开的作用域。 上游客户端请求该作用域,以便生成的访问令牌适用于代理。
不要向代理 API 发送为Microsoft Graph或其他资源颁发的令牌。
配置 sidecar 以验证代理 API 的受众和委托范围:
将 AzureAd:ClientId 设置为安装过程中记录的客户端 ID,而不是目录对象 ID。 将 AzureAd:Scopes 设置为 access_agent。 上游客户端请求 api://<agent-client-id>/access_agent。
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<tenant-id>",
"ClientId": "<agent-client-id>",
"Scopes": "access_agent"
}
}
使用同一 AzureAd 部分配置蓝图凭据。 有关完整的容器和凭据设置,请参阅 配置身份验证 SDK sidecar。
验证令牌
将完整的入站授权标头转发到 sidecar:
GET /Validate
Authorization: ******
响应包括已验证的协议、令牌和声明。 使用声明信息来标识用户并强制实施代理的授权策略。
在验证之前,不要信任客户端或代理解码的声明。
调用 sidecar
使用返回的声明之前,先使用 sidecar 验证入站授权标头。 要求protocol为Bearer,tid和oid声明非空,且access_agent位于以空格分隔的scp声明中。 通过组合 tid 和 oid标识调用方。 如果任何检查失败,请拒绝请求,并在处理请求之前应用代理的授权策略。
import requests
SIDECAR_URL = "http://localhost:5000"
def validate_caller(inbound_auth_header: str) -> dict:
"""Validate an inbound access token with the sidecar and return the token claims."""
response = requests.get(
f"{SIDECAR_URL}/Validate",
headers={"Authorization": inbound_auth_header},
timeout=5,
)
if response.status_code in (401, 403):
raise PermissionError("The sidecar rejected the caller's access token.")
response.raise_for_status()
result = response.json()
if result.get("protocol", "").lower() != "bearer":
raise PermissionError("The validated token used an unexpected protocol.")
claims = result.get("claims", {})
object_id = claims.get("oid")
tenant_id = claims.get("tid")
if not object_id or not tenant_id:
raise PermissionError("The validated token doesn't identify a user and tenant.")
if "access_agent" not in claims.get("scp", "").split():
raise PermissionError("The caller doesn't have the required delegated scope.")
return claims
# Call before processing each request:
claims = validate_caller(request.headers.get("Authorization"))
# Use claims["oid"] and claims["tid"] as the stable caller identity.
# Apply the agent's authorization policy before processing the request.
在共享网络命名空间中将 SIDECAR_URL 保持在回环接口上。 将授权标头占位符替换为代理接收的完整 Authorization 标头。 如果使用的是 access_agent 以外的范围,请同时更新 sidecar 配置和帮助程序的范围检查。
响应还包含已验证的令牌,但该示例不会反序列化它。 不要返回或记录令牌。 如果 sidecar 拒绝令牌,请拒绝代理请求,而不是在本地解码令牌或在没有经过身份验证的用户的情况下继续。
缺失或无效的令牌返回 401 Unauthorized,而经过身份验证的调用方缺少所需的范围或访问权限时返回 403 Forbidden。 在任一拒绝后不要继续访问下游 API。
该示例还拒绝由 Sidecar 通过另一种协议验证的凭据,例如仅限应用的所有权证明令牌。 使用经过验证的租户 ID 和对象 ID 作为稳定的用户密钥。 在处理请求之前应用代理的授权策略。