上游用戶端會讓使用者登入並向代理發送存取權杖。 代理程式會在使用使用者聲明或執行 On-Behalf-Of(OBO)交換前,先將該令牌傳給側車進行驗證。
側車並未提供登入的使用者介面。 在上游網頁、桌面或行動用戶端使用 MSAL。
Prerequisites
- 完成 「設定 Auth SDK sidecar」,包括代理程式的註冊與認證。
- 一個上游用戶端,負責讓使用者登入,並為代理程式公開的範圍請求權杖。
- 完成 「設定委派權限」 並 「授予上游用戶端存取權」。 這些註冊與 Microsoft Graph 同意步驟同樣適用於 sidecar;請勿使用該文章中的 ASP.NET Core 程式碼。
設定受眾
註冊由代理程式 API 公開的範圍權限。 上游用戶端會請求該權限範圍,因此產生的存取權杖是供代理程式使用的。
不要將為 Microsoft Graph 或其他資源發出的令牌傳送給代理程式 API。
設定 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 區段設定藍圖憑證。 如需完整的容器與認證設定,請參閱 「設定完整的 Auth SDK sidecar」。
驗證代幣
將完整的入站授權標頭轉送至側車:
GET /Validate
Authorization: ******
回應內容包含已驗證的協議、代幣與宣告。 使用宣告來識別使用者並強制執行代理程式的授權政策。
不要相信客戶端或代理程式在驗證前解碼的宣告。
叫用 sidecar
在使用側車回傳的聲明前,先使用側車驗證入站授權標頭。 要求 protocol 為 Bearer、非空的 oid 與 tid 宣告,以及 access_agent 在以空格分隔的 scp 宣告中。 透過 oid 和 tid 的組合來識別呼叫者。 若有任何檢查失敗,請拒絕該請求,並在處理前套用代理程式的授權政策。
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.
在共用網路命名空間中保留位於 loopback 上的 SIDECAR_URL。 將授權標頭佔位符替換為代理程式收到的完整 Authorization 標頭。 如果你使用 access_agent 以外的範圍,請同時更新側車設定和輔助程式的範圍檢查。
回應中也包含已驗證的標記,但範例並未將其反序列化。 不要退回或記錄該權杖。 如果 sidecar 拒絕該權杖,請拒絕代理程式要求,而不是在本機解碼權杖,或在沒有已驗證使用者的情況下繼續。
缺少或無效的權杖時,回傳 401 Unauthorized;當已驗證的呼叫者缺乏所需的範圍或存取權時,回傳 403 Forbidden。 在任一拒絕情況後,不要繼續使用下游 API。
此範例也拒絕了 sidecar 用其他協定(例如僅限應用程式的擁有權證明令牌)驗證的憑證。 使用已驗證的租戶 ID 與物件 ID 作為穩定使用者金鑰。 在處理請求前,請套用代理程式的授權政策。