Generating Azure OAuth2 Access Token By Python#
There are two modern ways to generate an Azure OAuth2 access token using Python: one is by using the MSAL library, and the other is by using the Azure Identity library, which is based on the former.
There're also other ways to get the token, like using the requests
or aiohttp
libraries etc. to send a POST request to the Azure OAuth2 token endpoint, but it's not recommended. As the MSAL and Azure Identity libraries are the official libraries provided by Microsoft, they are more secure and easier to use. For e.g. they handle token caching, token refreshing, and token expiration automatically. Furthermore, some of the credential types are difficult (too many code) to be implemented by raw requests
or aiohttp
.
Azure OAuth2 and OpenID Connect (OIDC)#
A quick summary of all the Azure OAuth2 and OpenID Connect (OIDC) flows:
- OAuth 2 Application types
- OAuth 2 and OpenID Connect (OIDC) Token grants flow
- Microsoft identity platform app types and authentication flows
MSAL library#
- ClientSecretCredential flow example
- Check the sample folder for the other flows
MSAL library does not support async
Check this GitHub issue for more information.
Azure Identity library is built on top of the MSAL library and supports async.
Azure Identity library#
- ClientSecretCredential flow example
- Async ClientSecretCredential flow example
- Async DefaultAzureCredential flow example
- All the available credential types:
- Check the sample folder for examples of some other flows (but not all of them).