[英]How to generate an on-behalf-of token for a middle-tier API
我正在嘗試使用 Microsoft Identity Platform 實現一個代表流程,我的 Web 應用程序在其中對用戶進行身份驗證,然后向我的 Web API 發出請求,后者又向 Microsoft Graph API 發出請求(並將結果返回給網絡應用程序)。
我的問題是,我需要將一個代表令牌傳遞給我的 Web API 才能獲得對 Microsoft Graph 的訪問權限,但我無法生成此令牌。 (我目前正在嘗試使用 Postman 生成此令牌。)
我希望能夠運行的是官方文檔here為Microsoft Graph SDK提供的代碼片段(在OBO流的情況下),我需要幫助的是如何為oboToken
變量生成令牌.
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Identity.Client;
var scopes = new[] { "User.Read", "Presence.Read.All" };
var tenantId = "common";
var clientId = "<id of my API as registered in Azure AD / App Registrations>";
var clientSecret = "<value from Client Secret in Registerd Application / Certificates & secrets";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var oboToken = "< WHAT NEEDS TO BE PROVIDED BY THE WEB APP >";
var cca = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authProvider = new DelegateAuthenticationProvider(async (request) => {
var assertion = new UserAssertion(oboToken);
var result = await cca.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
Console.WriteLine(graphClient.Me.Request().GetAsync().Result);
我嘗試了以下方法:我在瀏覽器中使用以下請求生成授權代碼
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=< Id of my API >
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp
&response_mode=query
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
然后,使用返回的代碼,發出以下 POST 請求(來自 Postman)
https://login.microsoftonline.com/common/oauth2/v2.0/token?
client_id=< Id of my API >
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp
&grant_type=authorization_code
&code=< code returned by request above >
當我使用從響應返回的令牌作為代碼片段中的oboToken
的值時,我得到一個
MsalServiceException:AADSTS50027:JWT 令牌無效或格式錯誤。
如果我在上面的 POST 請求中還包含一個client_secret
參數以獲取令牌,我會收到響應AADSTS90023: Public clients can't send a client secret 。
我怎樣才能生成一個代表令牌才能運行提供的代碼片段?
提前致謝!
在我看來,您的錯誤是使用授權代碼流獲取 MS Graph API 令牌。
它應該工作的方式是:
因此,當您的 Web 應用獲取訪問令牌時,它應該使用在 API 應用注冊中定義的范圍,而不是scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
。 如果您指定 MS Graph API 范圍,您將獲得 MS Graph API 的訪問令牌,這意味着您正在嘗試從 Web 應用程序調用 MS Graph API,而不是您的 API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.