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

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

问题描述

在Azure开发中,我们时常面临获取Authorization问题,需要使用代码获取到Access Token后,在调用对应的API,如servicePrincipals接口。 如果是直接调用AAD的 OAuth 2.0 接口,可以通过https://login.chinacloudapi.cn/{tenant}/oauth2/v2.0/token来获取Token。操作步骤在博文《使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization》中有详细描述。

 

而本次我们使用的是Python SDK (azure.common.credentials) 先获取到Access Token,然后调用Micrisoft Graph API接口,获取servicePrincipals信息。

问题解决

1) 在生成Access Token之前,需要准备好tenant_idclient_idclient_secret三个参数(在通过Azure AAD中获取)。获取方式可见文末 附录一

2) 然后调用credentials = ServicePrincipalCredentials(client_id, client_secret, tenant=tenant_id, resource='https://microsoftgraph.chinacloudapi.cn/', china='true')生成credentials对象。

3) 最后从credentials token中获取到需要的access token

from azure.common.credentials import ServicePrincipalCredentials
 
tenant_id="954ddad8-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx"
client_id="596e55da-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx"
client_secret="__Fa5.J.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxx"
credentials = ServicePrincipalCredentials(client_id, client_secret, tenant=tenant_id, resource='https://microsoftgraph.chinacloudapi.cn/', china='true')
access_token = credentials.token['access_token']
print(access_token)

获取ServicePrincipals的信息,调用接口:https://microsoftgraph.chinacloudapi.cn/v1.0/servicePrincipals

import urllib.request
import urllib
from flask import json
req = urllib.request.Request("https://microsoftgraph.chinacloudapi.cn/v1.0/servicePrincipals/%s" % (service_principaal_object_id))
req.add_header('Authorization', 'Bearer ' + access_token)
resp = urllib.request.urlopen(req)
content = resp.read()
content = json.loads(content)
#All content
print(content)
#print the application id 
print(content['appId'])

执行过程中错误

一:遇见 urllib.error.HTTPError: HTTP Error 401: Unauthorized 时,则要检查ServicePrincipalCredentials中设定的resource是否与被访问的API一致。

如时常出现Resource中设置为 https://graph.chinacloudapi.cn/。 而最后Request的URL Host为 https://microsoftgraph.chinacloudapi.cn/。 就会出现graph生成的Access Token无法访问microsoftgraph的资源。

 

二:遇见 urllib.error.HTTPError: HTTP Error 403: Forbidden时,则要查看当前使用的AAD应用的权限是否足够访问ServicePrincipal资源。检查方法如图:

 

参考文档

1) Overview of Microsoft Graphhttps://docs.microsoft.com/en-us/graph/overview?view=graph-rest-1.0

2) 使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorizationhttps://www.cnblogs.com/lulight/p/14279338.html

3) 关于application和service principal的区别:https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals

4) Get servicePrincipal:https://docs.microsoft.com/en-us/graph/api/serviceprincipal-get?view=graph-rest-1.0&tabs=http

 

附录一:在Azure AD中获取应用的Client id,tenant id,client_secret

 

  • 获取客户端密码[client_secret]
  • 在AAD应用页面,进入“证书和密码”页面,点击“新客户端密码”按钮,添加新的Secret(因密码值只能在最开始创建时可见,所以必须在离开页面前复制它

 

附录二:完整代码及运行结果

from azure.common.credentials import ServicePrincipalCredentials
import urllib.request
import urllib
from flask import json
service_principaal_object_id="954ddad8-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx"
tenant_id="954ddad8-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx"
client_id="596e55da-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx"
client_secret="__Fa5.J.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxx"
credentials = ServicePrincipalCredentials(client_id,client_secret, tenant=tenant_id,
                                             resource="https://microsoftgraph.chinacloudapi.cn/",china="true")
                                             
credentials = ServicePrincipalCredentials(client_id, client_secret, tenant=tenant_id, 
                                            resource='https://graph.chinacloudapi.cn/', china='true')
access_token = credentials.token['access_token']
print(access_token)
req = urllib.request.Request("https://microsoftgraph.chinacloudapi.cn/v1.0/servicePrincipals/%s" % (service_principaal_object_id))
req.add_header('Authorization', 'Bearer ' + access_token)
resp = urllib.request.urlopen(req)
content = resp.read()
content = json.loads(content)
#All content
print(content)
#print the application id 
print(content['appId'])

 

[完]

相关文章
|
6月前
|
供应链 搜索推荐 数据挖掘
探秘京东 API 接口的神奇应用场景
京东API如同数字钥匙,助力商家实现商品、库存、订单等多平台高效同步,提升效率超80%。支持物流实时追踪,增强用户满意度;赋能精准营销与数据分析,决策准确率提升20%以上,全面优化电商运营。
180 1
|
6月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
7月前
|
缓存 监控 算法
唯品会item_search - 按关键字搜索 VIP 商品接口深度分析及 Python 实现
唯品会item_search接口支持通过关键词、分类、价格等条件检索商品,广泛应用于电商数据分析、竞品监控与市场调研。结合Python可实现搜索、分析、可视化及数据导出,助力精准决策。
|
6月前
|
Ubuntu API C++
C++标准库、Windows API及Ubuntu API的综合应用
总之,C++标准库、Windows API和Ubuntu API的综合应用是一项挑战性较大的任务,需要开发者具备跨平台编程的深入知识和丰富经验。通过合理的架构设计和有效的工具选择,可以在不同的操作系统平台上高效地开发和部署应用程序。
272 11
|
7月前
|
缓存 监控 算法
苏宁item_get - 获得商品详情接口深度# 深度分析及 Python 实现
苏宁易购item_get接口可实时获取商品价格、库存、促销等详情,支持电商数据分析与竞品监控。需认证接入,遵守调用限制,适用于价格监控、销售分析等场景,助力精准营销决策。(238字)
|
7月前
|
Java API 开发者
揭秘淘宝详情 API 接口:解锁电商数据应用新玩法
淘宝详情API是获取商品信息的“金钥匙”,可实时抓取标题、价格、库存等数据,广泛应用于电商分析、比价网站与智能选品。合法调用,助力精准营销与决策,推动电商高效发展。(238字)
303 0
|
7月前
|
JSON 缓存 供应链
电子元件 item_search - 按关键字搜索商品接口深度分析及 Python 实现
本文深入解析电子元件item_search接口的设计逻辑与Python实现,涵盖参数化筛选、技术指标匹配、供应链属性过滤及替代型号推荐等核心功能,助力高效精准的电子元器件搜索与采购决策。
|
7月前
|
缓存 供应链 芯片
电子元件类商品 item_get - 商品详情接口深度分析及 Python 实现
电子元件商品接口需精准返回型号参数、规格属性、认证及库存等专业数据,支持供应链管理与采购决策。本文详解其接口特性、数据结构与Python实现方案。
|
6月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。

推荐镜像

更多