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 type Permissions (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后的結果:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM