【问题标题】:Implement Microsoft Graph API in a .netcore API project在 .net 核心 API 项目中实现 Microsoft Graph API
【发布时间】:2019-03-07 15:15:23
【问题描述】:

我正在尝试编写一个 .netcore API,它从第三方 Webapp 获取不记名令牌。此 .netcore API 应访问 Microsoft 图形 API 并从 Azure AD 获取用户组信息。

我正在关注示例项目https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

但不幸的是,这使用了 AAD 图形而不是 Microsoft 图形 API。

我尝试在上述示例中的 .netcore api 项目中实现 Graph API。

我尝试过的事情

我已将 AAD 图形更改为 AzureAdAuthenticationBuilderExtensions.cs(在 Web 应用项目中)中的图形 API

options.Resource = "https://graph.microsoft.com";

我还在 API 项目中使用了 Microsoft.Graph nuget。我正在尝试使用下面的代码创建 GraphServiceClient

public GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
    {
        var words = accessToken.Split(' ');
        var token = words[1];
        var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

            return Task.FromResult(0);
        });

        var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? new HttpProvider());

        return graphClient;
    }

最后我尝试使用下面的代码访问用户信息,

public async Task<IEnumerable<Group>> GetGroupAsync(string accessToken)
    {
        var graphClient = GetClient(accessToken);
        try
        {
            User me = await graphClient.Me.Request().GetAsync();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        var user= await graphClient.Users["***"].Request().Expand("MemberOf").GetAsync();


        var userEmail = "testemail@test.com";
        var usergroup = await graphClient.Users[userEmail].GetMemberGroups(false).Request().PostAsync();
        var groupList = new List<Group>();

        foreach (var g in usergroup.CurrentPage)
        {
            var groupObject = await graphClient.Groups[g].Request().GetAsync();
            groupList.Add(groupObject);
        }
        return groupList;
    }

但是当我尝试代码时,我收到错误“Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken 消息:访问令牌验证失败。Microsoft.Graph.HttpProvider 出现内部错误。”

有人可以帮帮我吗?

提前致谢

【问题讨论】:

  • 我遇到了同样的问题 - 你是如何解决的?如果您能分享代码,我将不胜感激

标签: .net-core asp.net-core-webapi


【解决方案1】:

传递给GetGroupAsync 的访问令牌不正确,我很困惑为什么需要拆分令牌:

var words = accessToken.Split(' ');
var token = words[1];

不过没关系,因为您已经修改了options.Resource = "https://graph.microsoft.com";,ADAL 将帮助您在OnAuthorizationCodeReceived 函数中获取 Microsoft Graph API 的访问令牌,并将令牌保存到缓存中。

要获取访问令牌,您可以使用 ADAL 从缓存中获取令牌:

AuthenticationResult result = null;
// Because we signed-in already in the WebApp, the userObjectId is know
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;

// Using ADAL.Net, get a bearer token to access the TodoListService
AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

然后您可以将该令牌传递给您的函数:

await GetGroupAsync(result.AccessToken);

修改您的 GetClient 函数以删除拆分部分:

public GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
{

    var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

        return Task.FromResult(0);
    });

    var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? new HttpProvider());

    return graphClient;
}

【讨论】:

  • 当我尝试上面的代码时,它在 HTTPContext.Session 处给了我一个错误,HTTPContext.Session 抛出了 System.InvalidOperationExeption 类型的异常
  • 您是否使用github.com/Azure-Samples/… 将令牌保存到缓存以及哪一行抛出错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-05
  • 2020-05-28
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多