1. 程式人生 > >【Azure Developer】使用Postman獲取Azure AD中註冊應用程式的授權Token,及為Azure REST API設定Authorization

【Azure Developer】使用Postman獲取Azure AD中註冊應用程式的授權Token,及為Azure REST API設定Authorization

Azure Active Directory (Azure AD) is Microsoft’s cloud-based identity and access management service, which helps your employees sign in and access resources in Azure.

問題描述

當我們使用REST API呼叫Azure上任何資源的時候,都需要在Request Header中提供Authorization的值。

 如何獲取Authorizatoin的值呢?

  • 一種快速的方式是訪問Azure門戶,通過F12(開發者工具)中檢視Network中請求的Header中的Authorization值。操作步驟見附錄一
  • 一種正規的方式是使用AAD API獲取Token。

以下內容則主要介紹如何通過AAD API獲取Token(常規的操作方式)。

 

操作步驟

一:先決條件

  • 在Azure Active Directory中已經註冊Application
  • 已安裝Postman

二:準備引數

1,獲取

  • 訪問AAD應用註冊連結:https://portal.azure.cn/?l=zh-hans.zh-cn#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps
  • 選中Application,等頁面載入完成後,選擇“終結點”按鈕。

2,獲取目錄(租戶) ID [tenant]

3,獲取

在應用的概述(Overview)頁面中複製出租戶(tenant),客戶端()。見上圖中的三組GUID數字。

4,獲取客戶端密碼[client_secret]

  • 在AAD應用頁面,進入“證書和密碼”頁面,點選“新客戶端密碼”按鈕,新增新的Secret(因密碼值只能在最開始建立時可見,所以必須在離開頁面前複製它

注:在呼叫OAuth 2.0獲取token時候,還需要設定scope和grant_type, 在當前示例中,分別使用https://microsoftgraph.chinacloudapi.cn/.default和client_credentials為值

scope:

https://microsoftgraph.chinacloudapi.cn/.default
grant_type: client_credentials

 

三:呼叫Token終結點

使用Postman呼叫Token終結點,全部的引數為:

請求方式 POST
請求URL https://login.chinacloudapi.cn/{TENANT}/oauth2/v2.0/token
請求Body

tenant:{TENANT}
client_id:{CLIENT ID}
scope:https://microsoftgraph.chinacloudapi.cn/.default
grant_type:client_credentials
client_secret:{SECRET VALUE}

請求成功後的響應Body

{     "token_type": "Bearer",     "expires_in": 3599,     "ext_expires_in": 3599,     "access_token": "eyJ0eXAiOiJKV1QiLCJub25jZSI6IjFJRk1tbFNMcnV1 ... ... ... ...  W0Da3_LzLhdNA" }

 

Postman截圖說明:

獲取到access_token的值後,即可作為Auzre REST API介面中Authroization的值。

 

四:解析Token

訪問https://jwt.io/,可以解碼Token內容,檢視當前Token中所攜帶的許可權(Role). 演示操作:

 

參考資料

什麼是 Azure Active Directory?https://docs.azure.cn/zh-cn/active-directory/fundamentals/active-directory-whatis
Microsoft Graph REST API v1.0 reference: https://docs.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0

 

附錄一:通過F12(開發者工具)中檢視Network中Request的Header中的Authorization值

&n