簡體   English   中英

如何在 asp net core mvc 應用程序中從我的 Azure AD B2C 獲取用戶列表?

[英]How to get list of Users from my Azure AD B2C in asp net core mvc app?

如何在 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 =>應用程序注冊(舊版) =>新應用程序注冊

在此處輸入圖像描述

記下應用 ID 並為您的應用創建密碼並記下: 在此處輸入圖像描述

此處將clinetID的值替換為 app id,並將client_secret的值替換為密碼。

授予讀取用戶對您的應用程序的權限: 在此處輸入圖像描述

在您的應用程序的 SELECT 權限之后單擊“授予權限”按鈕。

如果您有任何進一步的疑慮,請隨時告訴我。

請參考 Azure 圖表 API。

從文件:

The Azure Active Directory Graph API provides programmatic access to Azure AD through REST API endpoints. 應用程序可以使用 Azure AD Graph API 對目錄數據和對象執行創建、讀取、更新和刪除 (CRUD) 操作。 例如,Azure AD Graph API 支持用戶 object 的以下常用操作:

  • 在目錄中創建一個新用戶
  • 獲取用戶的詳細屬性,例如他們的組
  • 更新用戶的屬性,例如他們的位置和電話號碼,或更改他們的密碼
  • 檢查用戶的組成員資格以獲得基於角色的訪問
  • 禁用用戶的帳戶或完全刪除它

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api

這是一個演示項目,它向您展示如何列出 Azure B2C 目錄中的所有用戶:

https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet/blob/master/B2CGraphClient/B2CGraphClient.cs#L43-L110

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM