簡體   English   中英

獲取 Microsoft Graph API 的有效訪問令牌

[英]Obtaining a valid access token for Microsoft Graph API

我正在開發一個使用 Azure ADAL 庫對用戶進行身份驗證的 ASP.NET MVC5 Web 應用程序,它工作正常,但是,當我手動向圖形發送請求時,例如:GET https://graph.microsoft.com/v1.0 /me或 GET https://graph.microsoft.com/v1.0/groups ?$filter=from/displayName eq 'whatever'。

我嘗試更新 Azure 中的應用注冊以添加所需的 Graph 權限,並且我也嘗試創建新的應用注冊,無論我做什么,我的請求總是會響應 401 Unauthorized,有什么我遺漏的嗎?

編輯:來自郵遞員的示例響應

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError": {
      "request-id": "a142576b-acce-4e59-8a8d-adede61aaf59",
      "date": "2017-04-05T13:27:36"
    }
  }
}

編輯:C# 請求示例

public async Task<GroupGraph> GetGroupIdByDisplayName(string displayName)
{
    var accessToken = await authenticationService.GetTokenUserOnly();
    GroupGraph groupGraphResponse = null;
    using (var client = new HttpClient())
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, $"https://graph.microsoft.com/v1.0/groups?$filter=from/displayName eq '{displayName}'"))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                using (var response = client.SendAsync(request).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (var content = response.Content)
                        {
                            var result = await content.ReadAsStringAsync();
                            groupGraphResponse = JsonConvert.DeserializeObject<GroupGraph>(result);
                        }
                    }
                }
            }
        }
        return groupGraphResponse;
    }

編輯:我獲取令牌的方式

public async Task<string> GetTokenUserOnly()
    {
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential clientcred = new ClientCredential(clientId, appKey);
        // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new TableTokenCache(signedInUserID));
        //AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
        AuthenticationResult authenticationResult = authenticationContext.AcquireToken(graphResourceID, clientcred);
        return authenticationResult.AccessToken;
    }

您不能使用 ADAL 來獲取圖形的令牌。 微軟.com。 ADAL 用於圖形。 視窗.net。

為了獲取 Graph 庫 (graph.windows.com) 的令牌,請查看 Nuget 包 Microsoft.Graph。 Microsoft 也有一些關於如何使用 Graph 提取用戶信息的文檔

但請注意,同時使用圖形庫和 ADAL 庫可能會導致一些奇怪的副作用,例如憑據緩存被清除。

您似乎正在使用客戶端憑據授予流程來獲取圖形 api 的訪問令牌( graphResourceIDhttps://graph.microsoft.com ?):

  AuthenticationResult authenticationResult = authenticationContext.AcquireToken(graphResourceID, clientcred);

因此,您需要在 azure 廣告門戶中授予應用權限:

在此處輸入圖片說明

對於錯誤“訪問令牌驗證失敗”,您可以使用諸如http://jwt.calebb.net/ 之類的在線工具來解碼您的訪問令牌,檢查訪問令牌的受眾或生命周期。

要獲取 Microsoft Graph API 的有效令牌,您可以使用Azure.Identity

要使用TokenCredential任何實現,我們需要構建我們自己的IAuthenticationProvider

public class TokenCredentialAuthenticationProvider : IAuthenticationProvider
{
    private readonly TokenCredential _tokenCredential;

    public TokenCredentialAuthenticationProvider(TokenCredential tokenCredential)
    {
        _tokenCredential = tokenCredential;
    }
    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        var accessToken = await _tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { "https://graph.microsoft.com" }), CancellationToken.None);
        request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken.Token);
    }
}

例如,現在我們可以使用 AzureCliCredential 來獲取訪問令牌。

打開 Powershell 並輸入az login以使用您的 Azure AD 帳戶登錄。

在 Azure 中,您還可以使用Managed Identity來獲取基於 Azure 資源(例如 Azure 應用服務)的令牌。 這里需要使用ManagedIdentityToken

用法:

var client = new GraphServiceClient(new TokenCredentialAuthenticationProvider(new AzureCliCredential()));
var user = await client.Me.Request().GetAsync();

暫無
暫無

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

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