本段代码是个通用性很强的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赋予适当的权限

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订阅资源的目的。

AAD Service Principal获取azure user list (Microsoft Graph API)的更多相关文章

  1. 【Azure Developer】使用Microsoft Graph API 批量创建用户,先后遇见的三个错误及解决办法

    问题描述 在先前的一篇博文中,介绍了如何使用Microsoft Graph API来创建Azure AD用户(博文参考:[Azure Developer]使用Microsoft Graph API 如 ...

  2. 【Azure Developer】使用Microsoft Graph API 如何批量创建用户,用户属性中需要包含自定义字段(如:Store_code,Store_name等)

    Microsoft Graph 是 Microsoft 365 中通往数据和智能的网关. 它提供统一的可编程模型,可用于访问 Microsoft 365.Windows 10 和企业移动性 + 安全性 ...

  3. Microsoft Graph API -----起题 Graph API

    最近因为工作需要,接触学习使用了Microsoft Graph API.在看完Microsoft的Graph官方文档之后,也做了一些简单的案例,在Stack Overflow上做过一些回答.整体来说, ...

  4. 【Azure Developer】Python 获取Micrisoft Graph API资源的Access Token, 并调用Microsoft Graph API servicePrincipals接口获取应用ID

    问题描述 在Azure开发中,我们时常面临获取Authorization问题,需要使用代码获取到Access Token后,在调用对应的API,如servicePrincipals接口. 如果是直接调 ...

  5. 手把手:使用service principal连接Azure Media Service

    在简书中查看,请点击我. 关于相关内容解释,请参考docs文档 https://docs.microsoft.com/en-us/azure/media-services/previous/media ...

  6. 【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”

    问题描述 编写Java代码调用Mircrosoft Graph API创建用户时,分别遇见了"401 : Unauthorized"和"403 : Forbidden&q ...

  7. Azure登陆的两种常见方式(user 和 service principal登陆)

    通过Powershell 登陆Azure(Azure MoonCake为例)一般常见的有两种方式 1. 用户交互式登陆 前提条件:有一个AAD account 此种登陆方式会弹出一个登陆框,让你输入一 ...

  8. Azure App object和Service Principal

    为了把Identity(身份)和Access Management function(访问管理功能)委派给Azure AD,必须向Azure AD tenant注册应用程序.使用Azure AD注册应 ...

  9. 解决使用Microsoft Graph OAuth获取令牌时,没有refresh_token的问题

    今天在使用Microsoft Graph 的时候,发现按照官方文档,无论如何都不能获取refresh_token,其他都没问题,经过查询,发现是因为在第一步,获取code授权时,没有给离线权限(off ...

随机推荐

  1. 面试4——java进程和线程相关知识

    1.线程和进程的概念.并行和并发的概念

  2. Python高阶函数--map

    map()函数 map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把list 的每个元素依次作用在函数 f 上,得到一个新的 list 并返回. 例如,对于lis ...

  3. Bluedroid 函数分析:bta_dm_gattc_register

    我们先来看看在bluedroid 里面有多少地方调用到这里: 可以看出除了 它自己声明的地方,有三处 调用到这个函数. 一处是 进行discovery,一处是进行search的时候,还有一次是bta_ ...

  4. TiDB入门(四):从入门到“跑路”

    前言 前面三章基本把 TiDB 的环境弄好了,也做了一下简单测试,有兴趣的同学可以看一下: TiDB 入门(一):TiDB 简介 TiDB 入门(二):虚拟机搭建 TiDB-Ansible 部署方案 ...

  5. Facebook React 和 Web Components(Polymer)对比优势和劣势

    目录结构 译者前言 Native vs. Compiled 原生语言对决预编译语言 Internal vs. External DSLs 内部与外部 DSLs 的对决 Types of DSLs - ...

  6. awk技巧(如取某一行数据中的倒数第N列等)

    使用awk取某一行数据中的倒数第N列:$(NF-(n-1))比如取/etc/passwd文件中的第2列.倒数第1.倒数第2.倒数第4列(以冒号为分隔符) [root@ipsan-node06 ~]# ...

  7. Mysql之binlog日志说明及利用binlog日志恢复数据操作记录

    众所周知,binlog日志对于mysql数据库来说是十分重要的.在数据丢失的紧急情况下,我们往往会想到用binlog日志功能进行数据恢复(定时全备份+binlog日志恢复增量数据部分),化险为夷! 一 ...

  8. C_数据结构_递归实现求阶乘

    # include <stdio.h> int main(void) { int val; printf("请输入一个数字:"); printf("val = ...

  9. D. Fun with Integers

    链接 [http://codeforces.com/contest/1062/problem/D] 题意 给你n,让你从2到n这个区间找任意两个数,使得一个数是另一个的因子,绝对值小的可以变为绝对值大 ...

  10. Lotto HDU

    链接 [http://acm.hdu.edu.cn/showproblem.php?pid=1342] 题意 分析 DFS 代码 #include<cstdio> #include< ...