Trying to write a Python code where I would like to access my calendar and retrieve my schedule. Not able to get through the authentication phase. Seen and tested many examples, but all require running a local server where I browse locally and need to click a button and then enter my credentials. Aiming to perform all of this inside my Python code.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can achieve this one of two ways:
- Using Resource Owner Password Credential flow - This allows you to pass the username and password to Azure AD. Gotcha's here are if there's any extra thing on the auth flow (consent, MFA, password reset) you'll just get a failure.
- Using Client Credentials flow - This one requires admin consent. Also, you have to be really careful about this one as this client will have access to ALL info about all users. This should only be used with secure clients, not clients that other users have access to.
Here's a code snippet that showcases both of these:
import adal
import requests
tenant = "contoso.com"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
username = "foo@contoso.com"
password = "mypassword"
authority = "https://login.microsoftonline.com/" + tenant
RESOURCE = "https://graph.microsoft.com"
context = adal.AuthenticationContext(authority)
# Use this for Client Credentials
#token = context.acquire_token_with_client_credentials(
# RESOURCE,
# client_id,
# client_secret
# )
# Use this for Resource Owner Password Credentials (ROPC)
token = context.acquire_token_with_username_password(RESOURCE, username, password, client_id);
graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}'
# /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/
request_url = graph_api_endpoint.format('/me')
headers = {
'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
response = requests.get(url = request_url, headers = headers)
print (response.content)
回答2:
Will try the above...
What I did to solve this was using this example - https://developer.microsoft.com/en-us/graph/docs/authorization/app_only
The problem was asking for the right permissions for the app in Azure.