访问Microsoft Graph API数据时出现问题

时间:2019-04-30 14:57:16

标签: c# asp.net microsoft-graph asp.net-core-2.2

当前在将 Microsoft Graph API 集成到我的 ASP.NET Core 2.2 Web应用程序(MVC)中时遇到问题。使用“工作或学校帐户” “云–单一组织” ,并使用两要素Azure登录身份验证

使用代码示例1 代码,我正在尝试获取图形查询:-

https://graph.microsoft.com/v1.0/me/

从响应标题中返回姓氏

我目前遇到的问题是我在代码行收到错误:-

var objMessages = objGraphClient.Me.Request().GetAsync().Result;

出现错误消息:“ 不存在,或其查询的参考属性对象之一不存在”。

// #############
// Code Sample 1
// #############

// Graph Api.
string strResource = "https://graph.microsoft.com";
string SecretId = "<Secret Id>";

// Azure Ad.
Uri strInstance = new Uri("https://login.microsoftonline.com/");
string strDomain = "<Domain>.onmicrosoft.com";
string strTenantId = "<Tenant Id>";
string strClientId = "<Client Id>";
string strCallbackPath = "/signin-oidc";

// The authority to ask for a token: your azure active directory.
string strAuthority = new Uri(strInstance, strTenantId).AbsoluteUri;
AuthenticationContext objAuthenticationContext = new AuthenticationContext(strAuthority);
ClientCredential objClientCredential = new ClientCredential(strClientId, SecretId);

// Acquire Token.
AuthenticationResult objAuthenticationResult = objAuthenticationContext.AcquireTokenAsync(strResource, objClientCredential).Result;

// Get bearer token.
GraphServiceClient objGraphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async request =>
    {
    // This is adding a bearer token to the httpclient used in the requests.
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", objAuthenticationResult.AccessToken);
    }));

// The next line produces an error :: does not exist or one of its queried reference-property objects are not present.
var objResult = objGraphClient.Me.Request().GetAsync().Result;

Debug.WriteLine($"{objResult.Surname}");

如果我将上面的代码示例1 更改为下面的代码示例2 ,并传递了令牌Please(),则请求在成功登录后从Microsoft Graph Explorer获得该令牌,这可以正常工作,并返回姓氏成功,表明在我的Bearer令牌中这可能是一个问题:-

// #############
// Code Sample 2
// #############

// Get bearer token.
GraphServiceClient objGraphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async request =>
    {
    // This is adding a bearer token to the httpclient used in the requests.
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer","ERf54f2f...Etc");
    }));

// The next line now works.
var objResult = objGraphClient.Me.Request().GetAsync().Result;

Debug.WriteLine($"{objResult.Surname}");

对此将提供任何帮助!

1 个答案:

答案 0 :(得分:0)

您正在使用的ADAL库使用旧的Azure AD V1身份验证终结点。您应该使用使用Azure AD V2身份验证终结点的MSAL库。

我建议您使生活变得轻松,然后去获取Microsoft.Graph.Auth Nuget程序包,然后使用此代码,而不必创建自己的代码 DelegateAuthenticationProvider

IConfidentialClientApplication clientApplication = AuthorizationCodeProvider.CreateClientApplication(clientId, redirectUri, clientCredential);
AuthorizationCodeProvider authenticationProvider = new AuthorizationCodeProvider(clientApplication, scopes);