Microsoft Graph (2) API Call

  《Windows Azure Platform 系列文章目录

  

  调用Microsoft Graph API,分为四个主要步骤:

  一.注册应用 (App Registrations)

  二.登陆并获得Token

  三.授权

  四.Call API

  

  一.注册应用 (App Registrations)

  我们可以手动注册应用,然后获得:

  - Application (Client) ID

  - Directory (Tenant) ID

  - Client secrets

  有关这部分的详细内容,请参考:Windows Azure AD (7) 创建配置应用程序和服务主体 (Application and Service Principal)

  二.登陆并获得Token

  Microsoft Graph登陆分为两种方式:

  1.代表用户获取访问权限

  https://docs.microsoft.com/zh-cn/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 

  这种场景比较适合应用程序注册访问。比如我们开发的第三方APP应用程序,当进行登陆的时候,会通过Web页面进行登陆确认:

  

  2.无用户访问

  https://docs.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

  这种场景比较适合于后台服务进行调用,不存在用户登陆。比如我们自己开发的一个Windows Service程序,24*7的一直在运行。

  本文主要介绍的是无用户访问

  我们打开Postman,设置环境变量名称为:AzureChinaGraphConfig

  设置三个环境变量和参数值

  -tenant_id

  -app_id

  -app_secret

  

  然后在Postman中,Add New Request,设置一下内容:

  -名称设置为Get Graph Token

  -方法为POST,URL为:https://login.chinacloudapi.cn/{{tenant_id}}/oauth2/v2.0/token

  -设置body

参数 条件 说明
tenant 必须 我们在第一章注册应用中,设置的租户id,我们这里设置读取环境变量{{tenant_id}}
client_id 必须 我们在第一章注册应用中,设置的client_id,我们这里设置读取环境变量{{app_id}}
scope 必须 设置为:https://microsoftgraph.chinacloudapi.cn/.default
client_secret 必须 我们在第一章注册应用中,设置的client_secret,我们这里设置读取环境变量{{app_secret}}
grant_type 必须 设置为:client_credentials

  

  点击上图的Send后,获得的JWT如下图:

  

  我们把上图的access_token拿到后,可以在网站:https://jwt.ms/ 进行验证:

  

  三.授权Permission

  我们在访问Graph API的时候,还需要对API CALL进行授权。

  比如我们访问User API,https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http

  里面需要对API设置Permissions (授权),授权内容如下:

Permission typePermissions (from least to most privileged)
Delegated (work or school account) User.Read, User.ReadWrite, User.ReadBasic.All, User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All, Directory.AccessAsUser.All
Delegated (personal Microsoft account) User.Read, User.ReadWrite
Application User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All

  

  那如何进行授权呢?我们登陆到Azure China Porta:https://portal.azure.cn/

  点击下图,我们在步骤1中创建的application。

  

  在API Permissions里面,设置Add a Permission。如下图:

  

  先点击Microsoft Graph

  

  在弹出的窗口中,根据API需要的permission,设置Delegated Permission和Application Permissions

  

  

  设置完毕后,我们还要点击Grant admin consent for XXX

  

  四.Call API

  当设置完第三步的授权Permission后,我们就可以call API了

  例如我们要Get user:https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http

  需要call的URL是:https://microsoftgraph.chinacloudapi.cn/v1.0/users/

  HTTP Request: Get

  Request Headers

Header Value 说明
Authorization Bearer {token} 我们在步骤2中获得的Token
Content-Type application/json  

  CALL API后的结果:

  

原文地址:https://www.cnblogs.com/threestone/p/12821885.html