获取Microsoft Graph API的有效访问令牌

时间:2017-04-05 11:51:33

标签: azure oauth-2.0 azure-active-directory access-token microsoft-graph

我正在使用Azure ADAL库对用户进行身份验证的ASP.NET MVC5 Web应用程序,但是,当我手动向图表发送请求时,它工作正常,例如:GET https://graph.microsoft.com/v1.0/me或GET {{3 } $ filter = from / displayName eq'whatever'。

我尝试更新Azure中的App Registration以添加所需的Graph权限,我也尝试创建新的app注册,无论我做什么,我的请求总是会响应401 Unauthorized,我有什么遗漏吗?

编辑:Postman的回复示例

{
  "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;
    }

3 个答案:

答案 0 :(得分:1)

您无法使用ADAL获取图表的令牌。 microsoft .com。 ADAL用于图形。 windows .net。

为了获得Graph库(graph.windows.com)的令牌,请查看Nuget Package Microsoft.Graph。微软在如何使用Graph提取用户信息方面也有一些documentation

预先警告,并排使用图形库和ADAL库可能会导致一些奇怪的副作用,例如清除凭据缓存。

答案 1 :(得分:1)

您似乎正在使用客户端凭据授权流来获取图API的访问令牌(graphResourceIDhttps://graph.microsoft.com?):

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

因此,您需要在azure广告门户网站中授予应用程序权限:

enter image description here

错误&#34;访问令牌验证失败&#34; ,您可以使用http://jwt.calebb.net/等在线工具解码您的访问令牌,检查访问令牌的受众或生命周期。

答案 2 :(得分:0)

要获取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();