【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信息。
问题解决
在生成Access Token之前,需要准备好tenant_id,client_id,client_secret三个参数(在通过Azure AAD中获取)。获取方式可见文末 附录一
然后调用credentials = ServicePrincipalCredentials(client_id, client_secret, tenant=tenant_id, resource='https://microsoftgraph.chinacloudapi.cn/', china='true')生成credentials对象。
最后从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为

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

参考文档
Overview of Microsoft Graph:https://docs.microsoft.com/en-us/graph/overview?view=graph-rest-1.0
使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization:https://www.cnblogs.com/lulight/p/14279338.html
关于application和service principal的区别:https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals
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
- 访问AAD应用注册链接:https://portal.azure.cn/?l=zh-hans.zh-cn#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps
- 选中Application,等页面加载完成,页面中的应用程序(客户端)ID 和目录(租户)ID就是我们的Client ID, Tenant ID.

- 获取客户端密码[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'])

[完]
【Azure Developer】Python 获取Micrisoft Graph API资源的Access Token, 并调用Microsoft Graph API servicePrincipals接口获取应用ID的更多相关文章
- 使用GraphHttpClient调用Microsoft Graph接口 - PATCH
博客地址:http://blog.csdn.net/FoxDave 通过前两讲的阐述我们应该大致了解了使用GraphHttpClient调用Microsoft Graph接口的模式,并介绍了使用get ...
- 使用GraphHttpClient调用Microsoft Graph接口 - GET
博客地址:http://blog.csdn.net/FoxDave 使用GraphHttpClient类调用Microsoft Graph REST API,你可以使用GET,POST和PATCH请求 ...
- 使用GraphHttpClient调用Microsoft Graph接口 - POST
博客地址:http://blog.csdn.net/FoxDave 本篇接上一讲,我们继续看如何通过GraphHttpClient创建一个Office 365的组,需要使用POST请求. 为结果添加按 ...
- 在无人值守程序(服务)中调用Microsoft Graph
作者:陈希章 发表于 2017年5月31日 什么是无人值守程序(服务) 我在此前用了几篇文章分别介绍了在桌面应用程序(控制台),Web应用程序(ASP.NET MVC),以及PowerSehll脚本中 ...
- View and Data API tips: 缓存Access Token
对于云API服务,常见的方式就是按照API调用次数收费,某些API调用也就有某些限制,比如在特定时间内只允许调用指定的次数以免造成滥用.虽然Autodesk的view and Data API目前还没 ...
- 【转】asp获取【微信公众平台】Access Token的源代码下载
在做微信开发时候,经常要用到Access Token,但是官网提供的都是基于php写的,我用asp写了,有需要可以直接复制去用,模板消息,jdk上传图片,客服消息等全需要这个:'获取 access_t ...
- SharePoint Online 使用 adal js 获取access token
最近在写一些SharePoint 的sample code, 有兴趣的小伙伴可以查看我的GitHub. 今天给大家介绍SharePoint Framework (SPFx )web part 当中怎 ...
- 【Azure Developer】【Python 】使用 azure.identity 和 azure.common.credentials 获取Azure AD的Access Token的两种方式
问题描述 使用Python代码,展示如何从Azure AD 中获取目标资源的 Access Token. 如要了解如何从AAD中获取 client id,client secret,tenant id ...
- 【Azure Developer】使用Microsoft Graph API 批量创建用户,先后遇见的三个错误及解决办法
问题描述 在先前的一篇博文中,介绍了如何使用Microsoft Graph API来创建Azure AD用户(博文参考:[Azure Developer]使用Microsoft Graph API 如 ...
随机推荐
- httprunner(9)运行测试用例的方式总结
前言 用过pytest的小伙伴都知道,pytest的运行方式是非常丰富的,可以说是你想怎么运行怎么运行,想运行哪些运行哪些,那httprunner是否同样可以呢? 运行用例的各种方式 运行指定路径的用 ...
- Spring中AOP学习笔记
AOP 描述(摘抄百度百科) AOP开发中的相关操作术语 实例(xml方式) 通知的类型 切入点表达式的写法: 实例(注解方式) 描述(摘抄百度百科) AOP(面向切面编程):Aspect Orien ...
- 卸载vue2.9.6版本,安装新版本
1.检查vue安装目录(cmd中输入) where vue 2.删除目录中的关于vue的文件(可以将文件按时间排序,找到vue相关的文件删除) 3.检查vue是否还能找到 4.安装新版本的vue np ...
- 缓冲区溢出实验 2 sizeof/strlen
实验环境.代码.及准备 https://www.cnblogs.com/lqerio/p/12870834.html vul2 下面只给出有漏洞部分的代码.Vul2问题为sizeof函数在计算时会考虑 ...
- codeforces 2C(非原创)
C. Commentator problem time limit per test 1 second memory limit per test 64 megabytes input standar ...
- Leetcode(20)-有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 注意空字符串可被认 ...
- 2019牛客多校第五场C generator 2(BSGS)题解
题意: 传送门 已知递推公式\(x_i = a*x_{i - 1} + b\mod p\),\(p\)是素数,已知\(x_0,a,b,p\),给出一个\(n\)和\(v\),问你满足\(x_i = v ...
- linux通识
linux是服务器应用领域的开源且免费的多用户多任务操作系统的内核. 以下是对上述论断的解释: 操作系统 简言之,操作系统乃是所有计算设备的大管家,小到智能手表,大到航天航空设备,所有需要操控硬件的地 ...
- 关于谷歌浏览器不支持html5中audio的autoplay解决方法(js代码解决)
当我们直接写autoplay时,在chrome中浏览器并没有自动播放音频: 如果直接通过js来调用audio的play()方法也不行: 控制台还会报错 大概意思:play()调用失败,因为用户没有与文 ...
- macOS & PostgreSQL
macOS & PostgreSQL macOS 上安装 PostgreSQL 后为什么会自动创建一个系统用户账号 https://get.enterprisedb.com/postgresq ...