AAD Service Principal獲取azure user list (Microsoft Graph API)

本段代碼是個通用性很強的sample code,不只可以操做AAD自己,也能經過Azure Service Principal的受權來訪問和控制Azure的訂閱資源。(Azure某種程度上能當作是兩個層級:AAD+Subscription)

下文中的代碼是演示的screenshot中的紅字2的部分。紅字1的部分的permission實質上是賦予AAD service principal操做訂閱的權限(這個須要切換var resource = 「https://management.core.chinacloudapi.cn/「)api

預先準備

  1. 註冊一個Azure AD application
  2. 對這個aad application賦予適當的權限

sample code 以下:

  1 using Microsoft.IdentityModel.Clients.ActiveDirectory;
  2 using Newtonsoft.Json;
  3 using Newtonsoft.Json.Linq;
  4 using System;
  5 using System.Collections.Generic;
  6 using System.Collections.Specialized;
  7 using System.IO;
  8 using System.Linq;
  9 using System.Net;
 10 using System.Net.Http;
 11 using System.Net.Http.Headers;
 12 using System.Text;
 13 using System.Threading.Tasks;
 14  
 15 namespace AadGraphApi
 16 {
 17     class Program
 18     {
 19         static void Main(string[] args)
 20         {
 21             //Demo below AAD graph api
 22             //1. List All users in AAD
 23             //2. Check user existence
 24             //3. Get AppRoleAssignment
 25             //4. implement the appRoleAssignment
 26  
 27             //Test MoonCake Azure
 28             //Task task = CnTest();
 29  
 30             //Test Global Azure
 31             Task task = CnTest();
 32             var x = task;
 33             Console.WriteLine("**--------done-------**");
 34             Console.ReadLine();
 35         }
 36         // using Http Request to get Token
 37         private static async Task<string> CnAppAuthenticationAsync()
 38         {
 39             // Using in Mooncake Azure
 40             // Constants
 41             var tenant = "";
 42             var resource = "https://graph.chinacloudapi.cn";
 43             //var resource = "https://management.core.chinacloudapi.cn/";
 44             var clientID = "";
 45             var secret = "";
 46             // Ceremony
 47             var authority = $"https://login.chinacloudapi.cn/{tenant}";
 48             var authContext = new AuthenticationContext(authority);
 49             var credentials = new ClientCredential(clientID, secret);
 50             var authResult = await authContext.AcquireTokenAsync(resource, credentials);
 51             return authResult.AccessToken;
 52         }
 53  
 54         private static async Task CnTest()
 55         {
 56             var token = await CnAppAuthenticationAsync();
 57  
 58             using (var client = new HttpClient())
 59             {
 60                 //
 61                 //be careful for the specific parameters in the URI . replace it with yours
 62                 //
 63                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
 64  
 65                 var apiUriUserExist = new Uri("https://graph.chinacloudapi.cn/{yourtenantid}/users/**.partner.onmschina.cn?api-version=1.6");
 66                 var apiUriListAllUser = new Uri("https://graph.chinacloudapi.cn/**.partner.onmschina.cn/users?api-version=1.6");
 67                 var apiUriGetAppRoleAssignment = new Uri("https://graph.chinacloudapi.cn/**。partner.onmschina.cn/users/**.partner.onmschina.cn/appRoleAssignments?api-version=1.6");
 68  
 69                 //var userExist = await DoesUserExistsAsync(client, apiUriUserExist);
 70                 //Console.WriteLine($"Does user exists? {userExist}");
 71  
 72                 var userLists = await ListAllUsers(client, apiUriListAllUser);
 73                 Console.WriteLine(userLists);
 74                 /*
 75                 var appRoleList = await GetAppRoleAssignment(client, apiUriGetAppRoleAssignment);
 76                 Console.WriteLine(appRoleList);
 77  
 78                 //post request for AAD appRoleAssignment
 79                 await CnPostAppRoleAssignment(client);
 80                 //
 81                 */
 82             }
 83         }
 84  
 85         private static async Task<bool> DoesUserExistsAsync(HttpClient client, Uri apiUri)
 86         {
 87             try
 88             {
 89                 var payload = await client.GetStringAsync(apiUri);
 90                 return true;
 91             }
 92             catch (HttpRequestException)
 93             {
 94                 return false;
 95             }
 96         }
 97  
 98         private static async Task<string> ListAllUsers(HttpClient client, Uri apiUri)
 99         {
100             try
101             {
102                 var payload = await client.GetStringAsync(apiUri);
103                 return payload;
104             }
105             catch (HttpRequestException ex)
106             {
107                 return ex.ToString();
108             }
109         }
110     }
111 }

本段代碼經過受權去拿Azure AD 中的user。還有不少其餘的操做,好比delete user, list all user , Azure提供了一系列的Graph API 
同理咱們也能經過Managment受權發送操做資源的http請求達到代碼控制Azure訂閱資源的目的。app

相關文章
相關標籤/搜索