[英]How to get access token to call MS Graph on behalf of a user in the console app using MSAL?
[英]How to use MSAL to get access token on behalf of a user using AAD v1?
我有一個 Web 應用程序 (Angular 7),它使用MSAL Angular對 Azure AD 用戶進行身份驗證,並獲取訪問令牌以訪問我的 Web API (.NET 4.6)。 這兩個應用程序都已在 Azure 門戶中注冊,具有以下權限,如下所述:
user_impersonation
(委托)User.Read; Mail.Send
User.Read; Mail.Send
for MS Graph(委托)現在我想使用 ADAL for .NET 從 Web API 調用 Microsoft Graph,以代表用戶獲取一些數據。
按照此說明,我應該配置consentScopes
和protectedResourceMap
的資源映射,但由於我使用 AAD v1,因此我無法使用具有增量許可的范圍。
我應該如何配置我的 Web 應用程序以獲取 Web API 和 MS Graph 的訪問令牌?
我發現可以使用 MSAL.js 獲取 AAD v1.0 的令牌(並且我能夠與我的 Web API 進行通信),但我不知道如何配置它以代表用於通信 Web 的流帶有 MS Graph 的 API。
更新
以下是從 Web API 發出訪問令牌請求的代碼:
string accessToken = null;
var userAssertion = new UserAssertion(
<userAccessToken>,
"urn:ietf:params:oauth:grant-type:jwt-bearer",
userName);
var authority = "https://login.microsoftonline.com/" + <tenant> + "/";
var clientCredencial = new ClientCredential(<clientId>, <clientSecret>);
var authContext = new AuthenticationContext(authority, null);
try
{
var authResult = await authContext.AcquireTokenAsync(
"https://graph.microsoft.com",
clientCredencial,
userAssertion);
accessToken = authResult.AccessToken;
}
catch (AdalServiceException ex) { throw; }
Web App 在 Web API 清單中添加為knownClientApplications :
"knownClientApplications": [
"<WebAppAppId>"
],
這些是在 Web App (MsalModule) 中設置的范圍:
consentScopes:
[
'https://webapi.example.com/user_impersonation'
],
在這種情況下,Web App 在同意屏幕上需要以下權限:
如果我嘗試獲取 MS Graph 的訪問令牌,則會收到錯誤消息:
{“AADSTS65001:用戶或管理員未同意使用 ID 為“WebApiClientId”、名為“WebApiAppName”的應用程序。為此用戶和資源發送交互式授權請求。}
如錯誤消息所示,您缺少的是對 Web API 代表登錄用戶訪問 Microsoft Graph 的同意。
假設您已將 Web API 的應用注冊配置為需要 Microsoft Graph 的適當委派權限,您可以通過三個選項來提供所需的同意。
從 Azure 門戶提供管理員同意。 如果僅打算在您的租戶中使用,則租戶的管理員可以簡單地導航到 Web API 的應用程序注冊,並授予管理員對所需權限的同意。 (有關屏幕截圖和更多詳細信息,請參閱此答案的選項 1。)
通過構建適當的 URL 提供管理員同意。 使用門戶授予管理員同意的另一種方法是構建同意 URL。 在這種情況下,您將為 Web API 構建同意 URL。 (有關屏幕截圖和更多詳細信息,請參閱此答案的選項 2。)
在運行時,在同意 Web App 期間,利用knownClientApplications
。 如果將Web App的AppId
添加到Web API的應用注冊清單中的knownClientApplications
列表中,當要求用戶同意 Web App 時,也會提示他們同意 Web API 還需要的任何權限。 如果您使用 v2 端點登錄到 Web 應用程序(聽起來像您),則此方法僅在客戶端請求默認范圍(即預注冊權限,例如https://my.api.example.com/.default
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.