如何使用Microsoft Graph SDK通过电子邮件地址从Active Directory中获取用户信息
我们希望使用Microsoft Graph SDK从Azure Active目录中检索用户的信息.
We would like to retrieve user's information from Azure Active directory using Microsoft Graph SDK.
提供了一个有效的电子邮件地址,但我收到了错误消息
Given a valid email address, but I get an error
资源"myemailaddress@live.com"不存在,或者其查询的参考属性对象之一不存在.
Resource 'myemailaddress@live.com' does not exist or one of its queried reference-property objects are not present.
代码在下面.你能指导吗?
Code is below. Can you please guide?
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId).WithTenantId(tenantID).WithClientSecret(clientSecret).Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var user = await graphClient.Users["myemailaddress@live.com"].Request().GetAsync();
我可以重现您的问题.帐户myemailaddress@live.com
是租户中的Guest
,在门户中导航至AAD->找到该帐户->单击它并获取Object ID
,然后在代码中使用Object ID
,它将起作用
I can reproduce your issue. The account myemailaddress@live.com
is a Guest
in your tenant, navigate to the AAD in the portal -> find the account -> click it and fetch the Object ID
, then use the Object ID
in the code, it will work.
var user = await graphClient.Users["<Object ID>"].Request().GetAsync();
或者您可以使用filter
获取用户,在这种情况下,来宾用户的UserPrincipalName
格式类似于myemailaddress_live.com#EXT#@tenantname.onmicrosoft.com
,在使用过滤器时,我们需要对其进行网址编码将是myemailaddress_live.com%23EXT%23%40tenantname.onmicrosoft.com
,请尝试以下代码,它对我有效.
Or you can use filter
to get the user, in your case, the format of the UserPrincipalName
for the guest user will be like myemailaddress_live.com#EXT#@tenantname.onmicrosoft.com
, when using the filter, we need URL encode it, then it will be myemailaddress_live.com%23EXT%23%40tenantname.onmicrosoft.com
, try the code as below, it works on my side.
var user = await graphClient.Users.Request().Filter("UserPrincipalName eq 'myemailaddress_live.com%23EXT%23%40tenantname.onmicrosoft.com'").GetAsync();
更新:
如果您想通过UserPrincipalName
吸引用户,还可以使用如下所示的url编码.
If you want to get the user via UserPrincipalName
, you can also use the url encoded one as below.
var user = await graphClient.Users["myemailaddress_live.com%23EXT%23%40tenantname.onmicrosoft.com"].Request().GetAsync();