在.net核心API项目中实现Microsoft Graph API

问题描述 投票:0回答:1

我正在尝试编写.net核心API,它从第三方Web App获取持有者令牌。此.net核心API应访问Microsoft图形API并从Azure AD获取用户组信息。

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

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

我尝试在上面的示例中的.net核心api项目中实现Graph API。

我尝试过的事情

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

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 = "[email protected]";
        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 Message:Access token validation failed.Inner error at Microsoft.Graph.HttpProvider。”

有人可以帮帮我吗?

提前致谢

.net-core asp.net-core-webapi
1个回答
0
投票

传递给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;
}
© www.soinside.com 2019 - 2024. All rights reserved.