在.NETCORE API项目中实现Microsoft Graph API



我正在尝试编写一个.netcore API,该API从第三方WebApp获得了携带者令牌。此.NETCORE API应该访问Microsoft Graph API,并从Azure AD中获取用户组信息。

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

,但不幸的是,这使用了AAD图,而不是Microsoft Graph Api。

我尝试在上述样本中的.netcore API项目中实现图形API。

我尝试过的东西

我已将AAD图更改为Azureadauthenticationbuilderextensions.cs(在Web App Project)

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.httpprovider上的访问令牌验证失败。

有人可以帮我吗?

预先感谢

传递给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;
}

最新更新