使用Microsoft Graph

时间:2017-10-26 09:53:51

标签: microsoft-graph

我正在使用Microsoft Graph从我的应用程序访问Azure Active Directory,直接使用REST API(没有SDK)。

根据documentation,我应该可以使用iduserPrincipalName/users/{id | userPrincipalName}检索用户。

这确实有效,但不适用于访客用户。对于访客用户,userPrincipalName类似于name_originaldomain#EXT#@mydomain.onmicrosoft.com,并试图让用户获得404 Not Found的结果。

这是我目前使用的代码:

graphClient = new HttpClient();
graphClient.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
graphClient.DefaultRequestHeaders.Add("Authorization", $"{token.TokenType} {token.AccessToken}");

HttpRequestMessage request = new HttpRequestMessage(
    HttpMethod.Get,
    $"users/{Uri.EscapeUriString(username)}"
);

HttpResponseMessage response = await graphClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
    return await response.Content.ReadAsAsync<UserResult>();
}
// I am here with a 404

我错过了什么或做错了什么?

2 个答案:

答案 0 :(得分:3)

您需要对userPrincipalName进行编码。否则,您有效地传递了name_originaldomain,因为#将超出该点的所有内容指定为URI Fragment

尝试使用name_originaldomain%23EXT%23%40mydomain.onmicrosoft.com

答案 1 :(得分:3)

另一种方法是创建一个更大的查询,该查询还使用访客用户的电子邮件地址在mail属性上查询(或者在您的情况下使用“name @ originaldomain”查询)。对于访客用户,我们将邮件属性设置为访客的电子邮件地址。

../users?$filter=mail eq 'name@originaldomain'

希望这有帮助,