简体   繁体   English

在 Azure Active Directory 控制台代码 C# 中获取响应的问题

[英]Issue in getting response in Azure Active Directory console code C#

I am trying to execute below code to search a user in Azure Active Directory:我正在尝试执行以下代码以在 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();
          }
    }
}

But, I am unable to get anything in response and below line fails:但是,我无法得到任何回应,以下行失败:

HttpResponseMessage responsemMsg = await client.GetAsync(search_url);

Please help me fix this problem.请帮我解决这个问题。

As far as I know, you need to use Azure AD Graph API or Microsoft Graph API to retrieve a user.据我所知,您需要使用Azure AD Graph APIMicrosoft Graph API来检索用户。 And, Microsoft Graph API is now officially recommended.而且,现在正式推荐Microsoft Graph API

On the other hand, both Azure AD Graph API and Microsoft Graph API are protected by Azure AD which uses OAuth2 authorization, not basic authorization.另一方面,Azure AD Graph API 和 Microsoft Graph API 都受 Azure AD 保护,它使用 OAuth2 授权,而不是基本授权。 You may get-started with Authentication and authorization basics for Microsoft Graph你可以开始使用Microsoft Graph 的身份验证和授权基础知识

So, basically, you need to do the following steps:因此,基本上,您需要执行以下步骤:

  1. Register an app in Azure portal . 在 Azure 门户中注册应用程序 And
  2. Choose right scopes.选择正确的范围。 For example, the Get a user API needs one of the following permission:例如, 获取用户API 需要以下权限之一:

在此处输入图片说明

  1. Get access on behalf of a user (delegated permission) or Get access without a user (application permission) 代表用户获取访问权限(委托权限)或在没有用户的情况下获取访问权限(应用程序权限)

  2. Call Grapp API with token.使用令牌调用 Grapp API。 Here is a sample:这是一个示例:

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();
    }
}

Response:回复:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure Active Directory令牌缓存C#控制台应用程序 - Azure Active Directory Token Cache C# Console Application 从 C# 控制台应用程序访问 Azure Active Directory 并获得“权限不足,无法完成操作”。 错误信息 - Accessing Azure Active Directory from C# console app and getting "Insufficient privileges to complete the operation." error message Azure Active Directory C# - Azure Active Directory C# 使用 C# 代码从 Active Directory 获取当前登录信息 - Getting current login from Active Directory using C# code C#控制台应用程序,用于使用Microsoft Graph在Azure Active Directory中创建用户 - C# Console App to Create User in Azure Active Directory using Microsoft Graph 如何在 Azure Web App 中获取我的 C# 代码中的用户名? - How to get my Username in C# Code in Azure Web App while logged in with Azure Active Directory? 无法解决 C# Active Directory 控制台应用程序中的 Nuget 包 Microsoft.Graph.Auth 问题 - Unable to resolve Nuget package Microsoft.Graph.Auth issue in C# Active Directory console app 使用C#的Active Directory身份验证(编码问题) - Active Directory authentication with c# (encoding issue) 在C#中获取Active Directory用户 - Getting Active Directory user in C# 在C#中获取活动目录用户 - getting an active directory user in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM