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/“)

预先准备

  1. 注册一个Azure AD application
  2. 对这个aad application赋予适当的权限

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

sample code 如下:

 using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks; namespace AadGraphApi
{
class Program
{
static void Main(string[] args)
{
//Demo below AAD graph api
//1. List All users in AAD
//2. Check user existence
//3. Get AppRoleAssignment
//4. implement the appRoleAssignment //Test MoonCake Azure
//Task task = CnTest(); //Test Global Azure
Task task = CnTest();
var x = task;
Console.WriteLine("**--------done-------**");
Console.ReadLine();
}
// using Http Request to get Token
private static async Task<string> CnAppAuthenticationAsync()
{
// Using in Mooncake Azure
// Constants
var tenant = "";
var resource = "https://graph.chinacloudapi.cn";
//var resource = "https://management.core.chinacloudapi.cn/";
var clientID = "";
var secret = "";
// Ceremony
var authority = $"https://login.chinacloudapi.cn/{tenant}";
var authContext = new AuthenticationContext(authority);
var credentials = new ClientCredential(clientID, secret);
var authResult = await authContext.AcquireTokenAsync(resource, credentials);
return authResult.AccessToken;
} private static async Task CnTest()
{
var token = await CnAppAuthenticationAsync(); using (var client = new HttpClient())
{
//
//be careful for the specific parameters in the URI . replace it with yours
//
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var apiUriUserExist = new Uri("https://graph.chinacloudapi.cn/{yourtenantid}/users/**.partner.onmschina.cn?api-version=1.6");
var apiUriListAllUser = new Uri("https://graph.chinacloudapi.cn/**.partner.onmschina.cn/users?api-version=1.6");
var apiUriGetAppRoleAssignment = new Uri("https://graph.chinacloudapi.cn/**。partner.onmschina.cn/users/**.partner.onmschina.cn/appRoleAssignments?api-version=1.6"); //var userExist = await DoesUserExistsAsync(client, apiUriUserExist);
//Console.WriteLine($"Does user exists? {userExist}"); var userLists = await ListAllUsers(client, apiUriListAllUser);
Console.WriteLine(userLists);
/*
var appRoleList = await GetAppRoleAssignment(client, apiUriGetAppRoleAssignment);
Console.WriteLine(appRoleList); //post request for AAD appRoleAssignment
await CnPostAppRoleAssignment(client);
//
*/
}
} private static async Task<bool> DoesUserExistsAsync(HttpClient client, Uri apiUri)
{
try
{
var payload = await client.GetStringAsync(apiUri);
return true;
}
catch (HttpRequestException)
{
return false;
}
} private static async Task<string> ListAllUsers(HttpClient client, Uri apiUri)
{
try
{
var payload = await client.GetStringAsync(apiUri);
return payload;
}
catch (HttpRequestException ex)
{
return ex.ToString();
}
}
}
}

本段代码通过授权去拿Azure AD 中的user。还有很多其他的操作,比如delete user, list all user , Azure提供了一系列的Graph API
同理我们也能通过Managment授权发送操作资源的http请求达到代码控制Azure订阅资源的目的。

上一篇:阿里云ECS使用初体验


下一篇:stm32寄存器版学习笔记05 PWM