简体   繁体   中英

Querying Azure AD using c# console application

I am developing a simple c# console application to query Azure AD and fetch details of a given user. I found many useful articles on querying azure AD but none of them served my purpose. The sample codes posted on GitHub are way too lengthy and complicated for my simple requirement. I am using the code below, but i am getting a token error:

static async void MakeRequest()
        {
            var client = new HttpClient();

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



            // Specify values for the following required parameters
            queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            // var uri = "https://graph.windows.net/microsoft.onmicrosoft.com/users/{v-sidmis@microsoft.com}?" + queryString;

            var uri = "https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/users?api-version=1.6";

            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }


        }

I further searched for the token access and registered my app in the ad and used the below code:

var authContext = new AuthenticationContext("AUTHORITY");
            string token;
            try
            {
                //var authresult = authContext.AcquireToken("MYAPP_ID", "MYAPP_CLIENTID", "MYAPP_REDIRECTURI");
                var authresult = authContext.AcquireToken("https://graph.windows.net", "23b1c65e-5a20-4b88-a474-85c0845782c7", "https://localhost/");
                token = authresult.AccessToken;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

But not the getting the required result. Please help!!!

If you want to use graph API to get User info. You need to add token to your request header like following:

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", TokenForUser);

Here is the code snippet that could help to list User info, hope it could give you some tips:

 string AuthString = "https://login.microsoftonline.com/";
 string ResourceUrl = "https://graph.windows.net";
 string ClientId = "***";
 var redirectUri = new Uri("https://localhost");
 string  TenantId = "e4162ad0-e9e3-4a16-bf40-0d8a906a06d4";

 AuthenticationContext authenticationContext = new AuthenticationContext(AuthString+TenantId, false);
 AuthenticationResult userAuthnResult = await authenticationContext.AcquireTokenAsync(ResourceUrl,
     ClientId, redirectUri, new PlatformParameters(PromptBehavior.RefreshSession));
 TokenForUser = userAuthnResult.AccessToken;
 var client = new HttpClient();

 var uri = $"https://graph.windows.net/{TenantId}/users?api-version=1.6";
 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", TokenForUser);
 var response = await client.GetAsync(uri);
 if (response.Content != null)
 {
     var responseString = await response.Content.ReadAsStringAsync();
     Console.WriteLine(responseString);
 }

We could find ClientId, RedirectURi, tenantId, ResourceUrl in Azure AD native application:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM