Проблема при получении ответа в Azure Код консоли Active Directory C# - PullRequest
0 голосов
/ 10 февраля 2020

Я пытаюсь выполнить приведенный ниже код для поиска пользователя в Azure Active Directory:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.IO;

namespace AADConsoleApp
{
    class Program
    {
          static void Main(string[] args)
          {
             async System.Threading.Tasks.Task MySearchResult()
             {
                string search_url= "https://XXXXX-XXX.XX-XX.XXX.io/api/legacy/users?email=XXXX@XXX";

                try
                {
                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(
                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                                string.Format("{0}:{1}", "username", "password"))));

                    using (client)
                    {
                        HttpResponseMessage responsemMsg = await client.GetAsync(AD_API_Name_Search_URL);

                        Console.WriteLine("Hello");

                        if (responsemMsg.IsSuccessStatusCode)
                        {
                            var apiResponse = await responsemMsg.Content.ReadAsStringAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }

            MySearchResult();
          }
    }
}

Но я не могу получить что-либо в ответ, и ниже строки не удается:

HttpResponseMessage responsemMsg = await client.GetAsync(search_url);

Пожалуйста, помогите мне решить эту проблему.

1 Ответ

0 голосов
/ 11 февраля 2020

Насколько я знаю, вам нужно использовать Azure AD Graph API или Microsoft Graph API для получения пользователя. И, Microsoft Graph API теперь официально рекомендуется.

С другой стороны, Azure API Graph API и Microsoft Graph API защищены Azure AD, который использует авторизацию OAuth2, а не базовую c авторизацию. Вы можете начать с Основы аутентификации и авторизации для Microsoft Graph

Итак, в основном вам необходимо выполнить следующие шаги:

  1. Зарегистрироваться приложение в Azure портале . И
  2. Выберите правильные рамки. Например, для Get user API требуется одно из следующих разрешений:

enter image description here

Получить доступ от имени пользователя (делегированное разрешение) или Получить доступ без пользователя (разрешение приложения)

Позвоните в Grapp API с помощью токена. Вот пример:

class Program
{
    public static string GetDelegatedToken()
    {
        string token = null;

        using (HttpClient hc = new HttpClient())
        {
            hc.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");

            var body = new List<KeyValuePair<string, string>>();
            body.Add(new KeyValuePair<string, string>("grant_type", "password"));
            // Set scope
            body.Add(new KeyValuePair<string, string>("scope", "User.Read"));
            // The app id of the app you registered in Azure AD
            body.Add(new KeyValuePair<string, string>("client_id", "dc17****-****-****-****-****a5e7"));
            // The secret you created in your app
            body.Add(new KeyValuePair<string, string>("client_secret", "/pG******************32"));
            // Change it with your own user id
            body.Add(new KeyValuePair<string, string>("username", "jack@hanxia.onmicrosoft.com"));
            body.Add(new KeyValuePair<string, string>("password", "your password"));

            // Change e4c9ab4e-bd27-40d5-8459-230ba2a757fb with your tenant id
            var result = hc.PostAsync("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/oauth2/v2.0/token", new FormUrlEncodedContent(body)).Result;

            var json = JsonConvert.DeserializeObject<JObject>(result.Content.ReadAsStringAsync().Result);
            token = json["access_token"].ToString();
        }

        return token;
    }


    static void Main(string[] args)
    {
        using (HttpClient hc = new HttpClient())
        {
            hc.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
            hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetDelegatedToken());
            var result = hc.GetAsync("https://graph.microsoft.com/v1.0/users/jack@hanxia.onmicrosoft.com").Result;
            result.Content.CopyToAsync(Console.OpenStandardOutput()).GetAwaiter().GetResult();
        }
        Console.WriteLine();
    }
}

Ответ:

enter image description here

...