Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a guest user by userPrincipalName with Microsoft Graph

I am playing with Microsoft Graph to access Azure Active Directory from my application, using the REST API directly (without an SDK).

According to the documentation, I should be able to retrieve a user from their id or userPrincipalName using /users/{id | userPrincipalName}.

This is indeed working, but not for Guest users. With Guest users the userPrincipalName is something like name_originaldomain#EXT#@mydomain.onmicrosoft.com, and trying to get the user results in a 404 Not Found.

This is the code I am currently using:

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

Am I missing something or doing something wrong?

like image 224
Giorgio Di Nardo Avatar asked Oct 26 '17 09:10

Giorgio Di Nardo


2 Answers

You need to URL Encode the userPrincipalName. Otherwise you're effectively passing name_originaldomain since the # designates everything beyond that point as a URI Fragment.

Try using name_originaldomain%23EXT%23%40mydomain.onmicrosoft.com

like image 40
Marc LaFleur Avatar answered Sep 26 '22 15:09

Marc LaFleur


An alternative is to create a bigger query that also queries on the mail property with the guest user's email address (or in your case what you have as "name@originaldomain"). For guest users, we set the mail property to the guest's email address.

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

Hope this helps,

like image 67
Dan Kershaw - MSFT Avatar answered Sep 23 '22 15:09

Dan Kershaw - MSFT