Reputation: 514
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)
I'm trying to get list of available VM's, but I'm getting an error:
{'error': {'code': 'AuthorizationFailed', 'message': "The client 'X' with object id 'X' does not have authorization to perform action 'Microsoft.Compute/locations/vmSizes/read' over scope '/subscriptions/Y'."}}
Upvotes: 1
Views: 404
Reputation: 19223
Firstly, the api you used method is get
not post
.
Secondly, you need give your sp Owner
role, according to the error log, you don't give enough permission to your service principal, please see this link:assign-application-to-role.
I test in my lab, the following code works for me.
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
Upvotes: 1