如何在asp net核心MVC应用程序中从我的Azure AD B2C获取用户列表? [英] How to get list of Users from my Azure AD B2C in asp net core mvc app?
本文介绍了如何在asp net核心MVC应用程序中从我的Azure AD B2C获取用户列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在asp Net核心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=&>应用程序注册(旧版)=>;新应用程序注册:
记下应用程序ID并为您的应用程序创建密码并记下:
在此将clinetID
的值替换为应用ID,并将client_secret
的值替换为密码。
在为您的应用选择权限后,单击"授予权限"按钮。
如果您有任何进一步的问题,请随时让我知道。
这篇关于如何在asp net核心MVC应用程序中从我的Azure AD B2C获取用户列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文