from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import requests
client_id = *CLIENT_ID*
client_secret = *CLIENT_SECRET*
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token =oauth.fetch_token(token_url='https://login.microsoftonline.com/*TENANT_ID*/oauth2/token', auth=auth,resource= 'https://management.azure.com/')
data = {'Content-Type':'application/json',
'Authorization': 'Bearer ' + token['access_token']}
r =requests.post('https://management.azure.com/subscriptions/'
'*SUBSCRIPTION_ID*/providers/Microsoft.Compute/'
'locations/eastus/vmSizes?api-version=2016-04-30-preview', headers=data)
我试图获取可用虚拟机的列表,但我收到了错误消息:
{'错误':{'代码':'授权失败','消息':"客户' ; X'对象ID' X'没有授权执行操作' Microsoft.Compute / locations / vmSizes / read'超出范围' /订阅/ Y'。"}}
答案 0 :(得分:1)
首先,您使用的api方法是get
而不是post
。
其次,您需要提供sp Owner
角色,根据错误日志,您未向服务主管提供足够的权限,请参阅此{{3 }}
link:assign-application-to-role
我在我的实验室测试,以下代码适合我。
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import requests
client_id = ''
client_secret = ''
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token =oauth.fetch_token(token_url='https://login.microsoftonline.com/<tennat id>/oauth2/token', auth=auth,resource= 'https://management.azure.com/')
data = {'Content-Type':'application/json',
'Authorization': 'Bearer ' + token['access_token']}
r =requests.get('https://management.azure.com/subscriptions/<subscription id>/providers/Microsoft.Compute/locations/eastus/vmSizes?api-version=2016-04-30-preview', headers=data)
for i in r:
print i