【发布时间】: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