Cannot fetch users present in Azure AD from Microsoft graph API

Viewed 107

I have made a MVC application and I'm trying to add users to application.

The validation of user needs to be done through Azure AD for which Graph API is used.

Internal users presented in Azure AD are added successfully.

External users are also presented in Azure AD but I get the error

User not present in AD

I have tried applying all filters but still getting the same issue.

Code used:

var authProvider = await GetAuthProvider();
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

var user = await graphClient.Users[email].Request().GetAsync();
return true;

where email is the string of email passed from application. The code works fine for internal users but not for external users.

1 Answers

The issue is that you are using mail property but you should use userPrincipalName

mail has form like this

AdeleVance@adatum.com

but userPrincipalName for external user has different form

AdeleVance_adatum.com#EXT#@contoso.com
AdeleVance_adatum.com#EXT#@contoso.onmicrosoft.com

To query a external user using the userPrincipalName, encode the hash (#) character. Replace the # symbol with %23.

AdeleVance_adatum.com%23EXT%23@contoso.com

But graphClient should encode the hash character automatically.

Resources:

Get a user: HTTP request

Related