![](/img/trans.png)
[英]How to use MSAL to get access token on behalf of a user using AAD v1?
[英]How to get access token to call MS Graph on behalf of a user in the console app using MSAL?
我有一個 SPA 應用程序,它使用 AAD v2 身份驗證與我的后端 Web API 進行通信。 現在,我正在開發一個控制台應用程序,以代表登錄到 SPA 應用程序的用戶調用 Microsoft Graph。
我有一個有效的用戶訪問令牌(用於調用后端 Web API)。 我想使用這個訪問令牌來請求一個新的令牌來訪問 MS Graph。
以下是使用 MSAL.NET 請求具有 MS Graph 范圍的新訪問令牌的控制台應用程序的代碼:
string clientId = "<clientId>";
string clientSecret = "<clientSecret>";
string accessToken = "<validAccessTokenForWebApi>";
string assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
string[] scopes = new string[] { "User.Read", "Mail.Send" };
string graphAccessToken = null;
try
{
var app = ConfidentialClientApplicationBuilder
.Create(clientId).WithClientSecret(clientSecret).Build();
var userAssertion = new UserAssertion(accessToken, assertionType);
var result = app.AcquireTokenOnBehalfOf(scopes, userAssertion)
.ExecuteAsync().GetAwaiter().GetResult();
graphAccessToken = result.AccessToken;
}
catch (MsalServiceException ex)
{
throw;
}
但是當我調用app.AcquireTokenOnBehalfOf()
我得到一個異常:
AADSTS50013:斷言簽名驗證失敗。 [原因 - 提供的簽名值與預期的簽名值不匹配。,客戶端使用的密鑰指紋:'BB839F3453C7C04068B078EDADAB8E6D5F382E76',找到密鑰'Start=06/04/2019 00:00:00,End=06/04/2021 00:00:00']
是什么原因? 代表用戶獲取訪問令牌的正確方法是什么?
更新 - 為什么我需要控制台應用程序?
我可以直接從我的后端 API 調用 Graph API,但用戶可能會延遲某些操作(例如 30 分鍾后使用 Graph API 發送郵件)。 這就是為什么我需要使用按計划運行的控制台應用程序來執行此操作。
如果您想使用OAuth 2.0 On-Behalf-Of flow ,我認為您不需要開發控制台應用程序來調用圖形 api。 您可以直接使用后端 Web API 應用程序獲取訪問令牌,然后調用 Microsoft Graph。 根據我的理解,您只需執行這些步驟
有關詳細信息,請參閱示例。
關於如何在控制台應用程序中以代表流程獲取訪問令牌,詳細步驟如下。
注冊 web api 應用程序
注冊 SAP 應用
為 Web API 應用程序配置已知客戶端應用程序
在 Azure 門戶中,導航到您的 Web api 應用程序注冊,然后單擊清單部分。
找到屬性 knownClientApplications 並添加 SAP 應用程序的客戶端 ID
獲取訪問令牌以調用 web api
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize
?scope=<you web api scope> openid
&redirect_uri=<your sap app redirect url>
&nonce=test123
&client_id=<you sap app client id>
&response_type=id_token token
使用代表流程獲取訪問令牌
REST API
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
&client_id=<you web api client id>
&assertion=<you acess token you get in above steps>
&client_secret=<you app secret>
&scope=https://graph.microsoft.com/user.read
&requested_token_use=on_behalf_of
MSAL.net 代碼
string[] scopes = { "user.read" };
string accesstoken = "";
string appKey = "yor web api client secret";
string clientId = "your web api application id";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(appKey)
.Build();
UserAssertion userAssertion = new UserAssertion(accesstoken,
"urn:ietf:params:oauth:grant-type:jwt-bearer");
var result = app.AcquireTokenOnBehalfOf(scopes, userAssertion).ExecuteAsync().Result;
Console.WriteLine(result.AccessToken);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.