jjaskulowski
jjaskulowski

Reputation: 2574

Find user by name in Azure AD

I have this method to authenticate my application in AAD and read user unique ID by e-mail. Currently, I try to read anything about the user from AAD.

    private static async Task AddAzureUserFromEmail2(string email) {
        email = email.ToLowerInvariant();
        var client = new Microsoft.Graph.GraphServiceClient(
            "https://graph.windows.net/xyz.onmicrosoft.com",
            new DelegateAuthenticationProvider(
                async (request) => {
                    ClientCredential clientCred = new ClientCredential(
                        "cf4a6f4e-8b3f-4fdb-4450-19e9caa86123", // ID of app
                        "y728bjhjdfetrEsggddaauuyyttrreehjdffffdfdf="); // secret of app
                    var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/xyz.onmicrosoft.com", false);
                    var authenticationResult = await authenticationContext.AcquireTokenAsync("cf4a6f4e-8b3f-4fdb-4450-19e9caa86123", clientCred);
                    request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
                }));


        try {
            var user = await client.Users.Request().Select("mail").GetAsync();
        }
        catch (Exception ex) {
            //Here is error.
        }
    }

In try-catch block, I get

"Code: generalException Message: Unexpected exception returned from the service. "

What's wrong?

Upvotes: 0

Views: 485

Answers (2)

Dan Kershaw - MSFT
Dan Kershaw - MSFT

Reputation: 5838

Please check the documentation and schema for the Microsoft Graph user resource (see schema https://graph.microsoft.com/v1.0/$metadata OR documentation https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user).

Also Graph Explorer is a tremendous interactive tool for trying out Microsoft Graph. It's a bit like Postman, but exclusively for Microsoft Graph.

There is no email property on the user resource. There is a mail property that is set to the user's primary mail address. However this is set only if this value was set on-premises and sync'd to the cloud OR if the user is assigned an O365 license (and cloud mailbox).

Hope this helps,

Upvotes: 2

jjaskulowski
jjaskulowski

Reputation: 2574

I fixed the issue: I needed to use "https://graph.microsoft.com" as the resource name.

var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/dnv.onmicrosoft.com")

Upvotes: 0

Related Questions