簡體   English   中英

如何從 Azure Active Directory 獲取我的 API 和 Microsoft Graph 的有效訪問令牌?

[英]How to Get a valid access token for my API and Microsoft Graph from Azure Active Directory?

我正在嘗試設置一個 spa javascript 應用程序,該應用程序將用戶登錄到我們的 azure 活動目錄租戶,然后從 microsoft graph 檢索配置文件信息並調用用 c# 核心(我的 API)編寫的 azure 函數。

我為我的網站和 azure 活動目錄中的 api 設置了單獨的應用程序注冊。

我正在 javascript spa 網站中使用 MSAL.js 庫,並且我正在使用較新的 microsoft identity / v2.0 端點。

SPA 應用程序按預期登錄活動目錄,並能夠使用訪問令牌調用圖表以獲取配置文件信息。 在我的 azure 函數中,我驗證了令牌,但失敗並顯示錯誤“IDX10511:簽名驗證失敗。嘗試過的密鑰:.....”

現在,如果我在請求令牌時從范圍中刪除 Microsoft 圖形,我會得到一個令牌,該令牌在傳遞給 azure 函數時驗證得非常好,但我無法再在 spa 應用程序中檢索配置文件數據?

我如何讓兩者都工作?

還值得注意的是,我使用 jwt.io 測試了令牌,並且在使用圖形時也無法驗證簽名。

這是我獲取令牌的方式:

var msalConfig = {
  auth: {
    redirectUri: window.location.origin, // forces top level instead of specific login pages - fixes deep link issues.
    clientId: "Client ID of the website app", //This is your client ID
    authority:
      "https://login.microsoftonline.com/my-tennant-guid" //This is your tenant info
  },

  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true
  }
};
const msalUserAgent = new Msal.UserAgentApplication(msalConfig);


var requestObj = {
  scopes: ["User.Read", "api://MyApi/Access"]
};

//when the spa starts up I login using redirects
msalUserAgent.loginRedirect(requestObj);


//then before calling an api I request a token using this method
 acquireTokenSilent() {
    var promise = msalUserAgent.acquireTokenSilent(requestObj);
    return promise;
  },


嘗試在acquireTokenSilent() 函數中將scopes: ["User.Read"]指定為scopes: ["User.Read"] 由於訪問令牌僅對一個 API 有效。 如果您需要兩個,請使用不同的范圍兩次調用acquireTokenSilent。

登錄時可以為兩個 API 指定范圍,但在獲取令牌時則不能。 令牌具有指定目標 API 的受眾。 因此,您不能將一個 API 的令牌用於另一個 API。 這就是為什么它只對一個 API 有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM