使用Microsoft Graph通过userPrincipalName获取来宾用户

Gio*_*rdo 5 microsoft-graph

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

根据文档,我应该能够从用户iduserPrincipalName使用中检索用户/users/{id | userPrincipalName}

这确实有效,但不适用于Guest用户。对于Guest用户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
Run Code Online (Sandbox Code Playgroud)

我是否缺少某些东西或做错了什么?

Mar*_*eur 6

您需要对userPrincipalName. 否则,您实际上就通过了name_originaldomain,因为将#超出该点的所有内容都指定为URI Fragment

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

  • 我认为“Uri.EscapeUriString”可以解决问题,但结果是我应该使用“System.Net.WebUtility.UrlEncode”。谢谢马克。 (2认同)

Dan*_*SFT 6

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

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

希望这可以帮助,