【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'])
复制代码

 

[完]

posted @   路边两盏灯  阅读(790)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示