首页 > 解决方案 > 如何在 asp net core mvc 应用程序中从我的 Azure AD B2C 获取用户列表?

问题描述

如何在 asp net core mvc 应用程序中从我的 Azure AD B2C 获取用户列表?

标签: asp.net-core-mvcazure-ad-b2cazure-ad-graph-api

解决方案


您可以使用 Azure Graph API 来获取所有用户。在 .net 核心控制台应用程序中尝试以下代码:

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {

            var tenantID = "<your tenant ID>";
            var clinetID = "<your app id>";
            var client_secret = "<your app password>";

            HttpClient client = new HttpClient();
            
            //get access token from Azure AD 
            var reqContent = @"grant_type=client_credentials&resource=https://graph.microsoft.com&client_id="+ clinetID + "&client_secret="+ System.Web.HttpUtility.UrlEncode(client_secret);
            var Content = new StringContent(reqContent, Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = client.PostAsync("https://login.microsoftonline.com/"+ tenantID + "/oauth2/token", Content).Result;
            var token = JsonConvert.DeserializeObject<TokenResult>(response.Content.ReadAsStringAsync().Result);
           
            //Use access token to call microsoft graph api 
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.access_token);
            Console.WriteLine(client.GetAsync("https://graph.microsoft.com/v1.0/users").Result.Content.ReadAsStringAsync().Result); 
            
            Console.ReadKey();

        }
    }

    class TokenResult
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string ext_expires_in { get; set; }
        public string expires_on { get; set; }
        public string not_before { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
    }

}

要运行此代码,您应该在 B2C 租户中注册一个应用程序并授予读取用户权限: Azure Active Directory =>应用程序注册(旧版) =>新应用程序注册

在此处输入图像描述

记下应用 ID 并为您的应用创建密码并记下: 在此处输入图像描述

将 的值替换为clinetIDapp id 并在client_secret此处将 的值替换为密码。

授予读取用户对您的应用程序的权限: 在此处输入图像描述

为您的应用选择权限后,单击“授予权限”按钮。

如果您有任何进一步的疑虑,请随时告诉我。


推荐阅读