Dmi*_*try 5 asp.net-core-mvc azure-ad-graph-api azure-ad-b2c
如何从 asp net core mvc 应用程序中的 Azure AD B2C 获取用户列表?
您可以使用 Azure Graph API 来获取所有用户。在 .net core 控制台应用程序中尝试以下代码:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
要运行此代码,您应该在 B2C 租户中注册一个应用程序并为其授予读取用户权限: Azure Active Directory =>应用程序注册(旧版) =>新应用程序注册:
将 的值替换clinetID为应用程序 ID,并将 的值替换client_secret为密码。
为您的应用程序选择权限后,单击“授予权限”按钮。
如果您有任何进一步的疑虑,请随时告诉我。
| 归档时间: |
|
| 查看次数: |
6190 次 |
| 最近记录: |