I’m writing code to access the MS365 API and the Python code example uses urllib. I want to instead use requests but I’m not sure how urllib translates into requests as my attempts of doing so have failed.
The code example can be found here:
JavaScript
x
26
26
1
import json
2
import urllib.request
3
import urllib.parse
4
5
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
6
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
7
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
8
9
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
10
11
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
12
13
body = {
14
'resource' : resourceAppIdUri,
15
'client_id' : appId,
16
'client_secret' : appSecret,
17
'grant_type' : 'client_credentials'
18
}
19
20
data = urllib.parse.urlencode(body).encode("utf-8")
21
22
req = urllib.request.Request(url, data)
23
response = urllib.request.urlopen(req)
24
jsonResponse = json.loads(response.read())
25
aadToken = jsonResponse["access_token"]
26
Advertisement
Answer
Modifying @BeRT2me’s answer has made this work.
JavaScript
1
21
21
1
import requests
2
3
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
4
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
5
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
6
7
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
8
9
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
10
11
data = {
12
'resource' : resourceAppIdUri,
13
'client_id' : appId,
14
'client_secret' : appSecret,
15
'grant_type' : 'client_credentials'
16
}
17
18
response = requests.post(url=url, data=data)
19
jsonResponse = response.json()
20
aadToken = jsonResponse["access_token"]
21