[Azure Developer]使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization - LuBu0505/My-Code GitHub Wiki

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的值。 https://img2020.cnblogs.com/blog/2127802/202101/2127802-20210114192214615-1834048957.png

如何获取Authorizatoin的值呢?

  • 一种快速的方式是访问Azure门户,通过F12(开发者工具)中查看Network中请求的Header中的Authorization值。操作步骤见附录一
  • 一种正规的方式是使用AAD API获取Token。 以下内容则主要介绍如何通过AAD API获取Token(常规的操作方式)。

操作步骤

一:先决条件

  • 在Azure Active Directory中已经注册Application
  • 已安装Postman

二:准备参数

1,获取OAuth 2.0 令牌终结点(v2) [https://login.chinacloudapi.cn/{tenant}/oauth2/v2.0/token]

2,获取目录(租户) ID [tenant] 3,获取应用程序(客户端) ID[client_id] 在应用的概述(Overview)页面中复制出租户(tenant),客户端(client id)。见上图中的三组GUID数字。

4,获取客户端密码[client_secret] 在AAD应用页面,进入“证书和密码”页面,点击“新客户端密码”按钮,添加新的Secret(因密码值只能在最开始创建时可见,所以必须在离开页面前复制它) https://img2020.cnblogs.com/blog/2127802/202101/2127802-20210114200833416-1705847152.png

注:在调用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截图说明: https://img2020.cnblogs.com/blog/2127802/202101/2127802-20210114202320884-1596374516.png

获取到access_token的值后,即可作为Auzre REST API接口中Authroization的值。

四:解析Token

访问https://jwt.io/,可以解码Token内容,查看当前Token中所携带的权限(Role). 演示操作: https://img2020.cnblogs.com/blog/2127802/202101/2127802-20210114203338989-1523221195.gif

参考资料 什么是 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值

(注:在使用REST API接口时,需要主要所使用的资源与Azure 门户中资源要相同。这是因为Azure门户中,不同资源所生成的Authorization值各不相同,如不注意,也会遇见无权限401错误)