簡體   English   中英

Microsoft Graph API 令牌驗證失敗

[英]Microsoft Graph API token validation failure

我會在我的 Angular Web 應用程序中使用 Microsoft Graph API。

首先,我使用msal 庫進行連接當我嘗試使用我的個人資料登錄時,出現此錯誤

我已將我的應用程序配置為官方git 示例中提到的

MsalModule.forRoot({
  clientID: "Tenant ID",
  authority: "https://login.microsoftonline.com/common/",
  redirectUri: "http://localhost:4200/",
  validateAuthority : true,
  popUp: true
}),

身份驗證正在運行,我得到了令牌。

然后,當我進入主頁時,我向 Microsoft Graph API 發出第二個請求,以使用該令牌獲取用戶信息。

getProfile() {
  let header= new Headers();
  let tokenid= sessionStorage.getItem('msal.idtoken'); 
  header.set('Authorization', 'Bearer ' + tokenid)
  let url ="https://graph.microsoft.com/v1.0/me/"
  return this.http.get(url,{headers:header});
}

}

我收到一個 401 Unauthorized 錯誤的響應:

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError": {
      "request-id": "xxxxxx",
      "date": "2018-10-09T22:58:41"
    }
  }
}

我不知道為什么 MG API 不接受我的令牌,我是否使用了錯誤的授權網址?

更新:我知道實際上我得到了與訪問令牌不同的 id_token。 如何從 MSAL 庫獲取訪問令牌以進行 MS GRAPH API 調用?:

根據同一個示例,您還可以附加一個HttpInterceptor ,它將自動將訪問令牌附加到每個(外部)HTTP 調用。

通過閱讀文檔,我發現了以下信息。

同意范圍允許客戶端表達應同意的所需范圍。 范圍可以來自多個資源/端點。 在這里傳遞范圍只會同意它,並且在客戶端實際調用 API 之前不會獲取訪問令牌。 如果您僅將 MSAL 用於登錄(身份驗證),則這是可選的。

這表明使用HttpInterceptor不僅附加訪問令牌,而且還檢索它。 您看到的令牌可能只是您的應用程序的令牌,但不是 Graph API 的有效令牌。

在內部,它使用getCachedTokenInternal(scopes: Array<string>, user: User)來獲取此處找到的特定范圍代碼的新訪問令牌。 我不確定您是否也可以使用此方法來獲取該資源的新令牌。 我只會使用攔截器。

您可以嘗試復制訪問令牌並查看它在jwt.ms (Microsoft 提供的 JWT 令牌查看器)或jwt.io 上的樣子

任何對 Graph 有效的令牌都應該具有https://graph.microsoft.com受眾,因此如果您檢查令牌(在 jwt.ms 中),它至少應該具有此值。

"aud": "https://graph.microsoft.com",

問題是您使用的是 id_token 而不是訪問令牌:

let tokenid= sessionStorage.getItem('msal.idtoken');

變成這樣:

let tokenid= sessionStorage.getItem('msal.token'); // or msal.accesstoken

更新(根據菲利普的評論)

您需要選擇要在應用程序中定位的范圍。 因此,您似乎需要用戶配置文件,因此您需要添加 permitScopes 屬性來指定您的應用將使用哪些范圍:

MsalModule.forRoot({
  clientID: "Tenant ID",
  authority: "https://login.microsoftonline.com/common/",
  redirectUri: "http://localhost:4200/",
  validateAuthority : true,
  popUp: true,
  consentScopes: ["user.read"]
}),

確保將端點添加到資源映射配置中。 請參閱此鏈接: https : //github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp

export const protectedResourceMap:[string, string[]][]=[ ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];

暫無
暫無

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

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