asp.net-core-mvc - 如何在 asp net core mvc 应用程序中从我的 Azure AD B2C 获取用户列表?
问题描述
如何在 asp net core mvc 应用程序中从我的 Azure AD B2C 获取用户列表?
解决方案
您可以使用 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 =>应用程序注册(旧版) =>新应用程序注册:
将 的值替换为clinetID
app id 并在client_secret
此处将 的值替换为密码。
为您的应用选择权限后,单击“授予权限”按钮。
如果您有任何进一步的疑虑,请随时告诉我。
推荐阅读
- r - 传递反应数据作为 updateSelectizeInput 的选择
- c# - 带有 .Net Core 2.0 WebApi System.TypeLoadException 的 RazorLight
- python - 在 Beautifulsoup 中使用 find_all 选择两个特定的类
- java - 文件IP.exists(); 不返回真
- visual-studio - Visual Studio 安装程序下载停止在 5MB
- javascript - React 中的路径名条件渲染
- javascript - JS 中的 parseFloat 用于德语表示法
- hdfs - Hadoop 3.0 纠删码 - 确定可接受的节点故障数?
- javascript - 将 JQuery show() 替换为纯 javascript
- c++ - 构造函数不会将用 new 初始化的数组作为参数