Riz
Riz

Reputation: 6676

microsoft graph api sdk fails to retrieve user by principalname/email

I am getting the following error:

Code: Request_ResourceNotFound
Message: Resource '[email protected]' does not exist or one of its queried reference-property objects are not present.

I am trying to retrieve a user by email from my AD B2C tenant using the graph sdk like so:

public static GraphServiceClient GetGraphServiceClient()
{
    var clientapp = ConfidentialClientApplicationBuilder
        .Create(Globals.ClientId)
        .WithTenantId(Globals.TenantId)
        .WithClientSecret(Globals.ClientSecret)                
        .Build();

    ClientCredentialProvider authProvider = new ClientCredentialProvider(clientapp);

    return new GraphServiceClient(authProvider);
}



public static async Task<User> GetADUserAsyncByEmail(string email)
        {
            var graphClient = GetGraphServiceClient();
            try
            {
                var user = await graphClient.Users[email].Request().GetAsync();
                return user;
            }
            catch(ServiceException ex)
            {
                return null;
            }
            catch( Exception ex)
            {
                return null;
            }
            
        }

Upvotes: 1

Views: 940

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59318

It appears the user you are trying to get corresponds to consumer user, if so it needs to be addressed by issuer and issuerAssignedId where:

  • issuer is a B2C tenant name
  • issuerAssignedId is an email address of the user account

Example

var tenant = "{tenant-prefix}.onmicrosoft.com";
var signInName = "[email protected]"; 
        
var users = await graphClient.Users
            .Request()
            .Filter($"identities/any(c:c/issuerAssignedId eq '{signInName}' and c/issuer eq '{tenant}')")
            .Select("displayName,id,userPrincipalName")
            .GetAsync();

 var foundUser = users.FirstOrDefault();
 

Refer an example from official documentation

Upvotes: 2

Related Questions