Search code examples
c#asp.net-coreazure-active-directorymicrosoft-graph-apimicrosoft-graph-sdks

Get User by email address using Microsoft Graph API


I am trying to get the information if the user Exists (using email Address) in Azure AD or not using Microsoft Graph API (Version 5.17.0).

 var myself = await _graphServiceClient.Me.GetAsync();  // This Code Works

 var user = await _graphServiceClient.Users.GetAsync(c =>
                {
                    c.QueryParameters.Select = new[] { "mail" };
                    c.QueryParameters.Top = 1;
                    c.QueryParameters.Filter = $"mail eq {userEmail}";
                })!.Value?.FirstOrDefault();  // This doesn't work

I am getting an exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown.

Here are my settings in appsettings.json

  "GraphApi": {
      "BaseUrl": "https://graph.microsoft.com/v1.0",
      "Scopes": "User.Read.All"
  }

Also, I have given permissions Users.Read.All on Azure Portal enter image description here

Here is my code while Configuration

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration)
            .AddMicrosoftGraph(Configuration.GetSection("GraphApi"))
            .AddInMemoryTokenCaches();

Couldn't figure out what else I am missing.


Solution

  • Eventually, I figured it out,

    I had to use this to get user by email address

    var result = await _graphServiceClient.Users[userEmail].GetAsync();