You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: msal-python-conceptual/getting-started/acquiring-tokens.md
+20-20Lines changed: 20 additions & 20 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
---
2
2
title: Acquire tokens for your app
3
-
description: Learn how to acquire tokens for your Python appliccation. You can acquire tokens silently or interactively through a web browser.
3
+
description: Learn how to acquire tokens for your Python application. You can acquire tokens silently or interactively through a web browser.
4
4
author: SHERMANOUKO
5
5
manager: CelesteDG
6
6
ms.service: msal
@@ -19,11 +19,11 @@ There are many ways of acquiring a token with MSAL Python. Some require user int
19
19
20
20
## Prerequisites
21
21
22
-
Before you acquire tokens with MSAL Python, make sure learn how to instantiate a [client application](./client-applications.md).
22
+
Before you acquire tokens with MSAL Python, learn about [types of client application](./client-applications.md).
23
23
24
24
## Get user account
25
25
26
-
An app can acquire a token as itself or on behalf of a user. To acquire a token on behalf of a user, the app needs to know the user's account. MSAL Python provides the [`get_accounts`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-get-accounts) method to get the user's account. This method is available on both [`PublicClientApplication`](/python/api/msal/msal.application.publicclientapplication) and [`ConfidentialClientApplication`](/python/api/msal/msal.application.confidentialclientapplication) classes. The method returns a list of accounts which you the user has previously signed in with, that is, exists in cache.
26
+
An app can acquire a token as itself or on behalf of a user. To acquire a token on behalf of a user, the app needs to know the user's account. MSAL Python provides the [`get_accounts`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-get-accounts) method to get the user's account. This method is available on both [`PublicClientApplication`](/python/api/msal/msal.application.publicclientapplication) and [`ConfidentialClientApplication`](/python/api/msal/msal.application.confidentialclientapplication) classes. The method returns a list of accounts that the user has previously signed in with, that is, exists in cache.
@@ -36,17 +36,17 @@ The account selected by the user for sign-in can later be used in `acquire_token
36
36
There are several authentication flows that can be used to acquire tokens with MSAL Python. You can find more information on these flows on the [Microsoft identity platform documentation](/entra/identity-platform/v2-oauth2-auth-code-flow).
37
37
38
38
> [!WARNING]
39
-
> Always use MSAL to handle to get security tokens and call protected web APIs in your apps. We don't recommend you implementing your own token acquisition logic. These flows are to help you have a better understanding of how things work. If you are securing a web application, we recommend using the [identity](https://pypi.org/project/identity/) library. This library is not officially maintained by Microsoft but it implements most of the logic you need to acquire tokens in web apps.
39
+
> Always use MSAL to handle to get security tokens and call protected web APIs in your apps. We don't recommend you implementing your own token acquisition logic. These flows are to help you have a better understanding of how things work. If you are securing a web application, we recommend using the [identity](https://pypi.org/project/identity/) library. This library isn't officially maintained by Microsoft but it implements most of the logic you need to acquire tokens in web apps.
40
40
41
41
## Interactive vs silent
42
42
43
43
MSAL Python supports both interactive and silent token acquisition. Interactive token acquisition requires user interaction, while silent token acquisition doesn't. Public clients generally require user interaction while confidential clients rely on pre-provisioned credentials, like certificates and secrets.
44
44
45
-
Use the [`acquire_token_silent_with_error`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-acquire-token-silent-with-error) method to silently acquire a token. This method finds a valid access token from cache, or a valid refresh token from cache and then automatically use it to redeem a new access token. If neither is true, you'll need to use an interactive method to acquire the token.
45
+
Use the [`acquire_token_silent_with_error`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-acquire-token-silent-with-error) method to silently acquire a token. This method finds a valid access token from cache, or a valid refresh token from cache and then automatically use it to redeem a new access token. If neither is true, you need to use an interactive method to acquire the token.
46
46
47
47
If your app doesn't care about the exact token refresh error during token cache look-up, then the [`acquire_token_silent`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-acquire-token-silent) method is recommended.
48
48
49
-
An example usage of this method(s) is as shown in the following code snippet.
49
+
An example usage of this method is as shown in the following code snippet.
50
50
51
51
```python
52
52
if accounts:
@@ -68,17 +68,17 @@ if accounts:
68
68
print(result.get("correlation_id")) # You may need this when reporting a bug
69
69
```
70
70
71
-
Several methods are available for interactive token acquisition. The method to use depends on the type of app you are building and the token grant flow applicable to your scenario.
71
+
Several methods are available for interactive token acquisition. The method to use depends on the type of app you're building and the token grant flow applicable to your scenario.
72
72
73
73
## Public clients interactive token acquisition
74
74
75
-
Public client applications can't securely store a secret and can only authenticate the user that is interacting with the product. MSAL Python exposes most of the token acquisition logic for public applications through [`PublicClientApplication`](xref:msal.application.PublicClientApplication). Using this class enables developers to:
75
+
Public client applications can't securely store a secret and can only authenticate the user that is interacting with the product. MSAL Python exposes the token acquisition logic for public applications through [`PublicClientApplication`](xref:msal.application.PublicClientApplication). The following are the different methods available for public client applications to acquire tokens.
76
76
77
77
### Device code flow
78
78
79
-
For applications running on devices which don't have a web browser, it's possible to acquire a token through the [device code flow](/entra/identity-platform/v2-oauth2-device-code), which provides the user with a URL and a code. The user goes to a web browser on another device, enters the code and signs in. On successful authentication, Microsoft Entra will return a token to the browser-less device.
79
+
For applications running on devices that don't have a web browser, it's possible to acquire a token through the [device code flow](/entra/identity-platform/v2-oauth2-device-code). This flow provides the user with a URL and a code. The user goes to a web browser on another device, enters the code and signs in. On successful authentication, Microsoft Entra returns a token to the browser-less device.
80
80
81
-
First, you'll need to call the [`initiate_device_flow`](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-initiate-device-flow) method
81
+
First, youcall the [`initiate_device_flow`](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-initiate-device-flow) method.
@@ -93,7 +93,7 @@ sys.stdout.flush() # Some terminal needs this to ensure the message is shown
93
93
# input("Press Enter after signing in from another device to proceed, CTRL+C to abort.")
94
94
```
95
95
96
-
You then pass the flow dictionary object to the [`acquire_token_by_device_flow`](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-acquire-token-by-device-flow) method to get the token. By default, this method will block the current thread. You can follow [these instructions](https://msal-python.readthedocs.io/en/latest/#msal.PublicClientApplication.acquire_token_by_device_flow) to shorten the block time or you may even turn off the blocking behavior and then keep calling [`acquire_token_by_device_flow`](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-acquire-token-by-device-flow) in your own customized loop.
96
+
You then pass the flow dictionary object to the [`acquire_token_by_device_flow`](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-acquire-token-by-device-flow) method to get the token. By default, this method blocks the current thread. You can follow [these instructions](/python/api/msal/msal.application.publicclientapplication#msal-application-publicclientapplication-acquire-token-by-device-flow) to shorten the block time or you can even turn off the blocking behavior and then keep calling `acquire_token_by_device_flow` in your own customized loop.
97
97
98
98
```python
99
99
result = app.acquire_token_by_device_flow(flow)
@@ -108,7 +108,7 @@ A successful response a dictionary with an `access_token` key.
108
108
109
109
### Acquire token interactive
110
110
111
-
MSAL Python also offers the ability for public client apps (Desktops and Mobile) to acquire tokens as the user with the help of an interactive flow after letting the user sign-in through the authorization request URL via a web browser. You'll need to set the redirect URI of your app to `http://localhost` in the Microsoft Entra admin center for your app registration. If you opt in to use broker during `PublicClientApplication` creation, your app also needs `ms-appx-web://Microsoft.AAD.BrokerPlugin/YOUR_CLIENT_ID` as a redirect URI.
111
+
MSAL Python also offers the ability for public client apps (Desktops and Mobile) to acquire tokens as the user. The user signs in through the authorization request URL via a web browser. Set the redirect URI of your app to `http://localhost` in the Microsoft Entra admin center for your app registration. If you opt in to [use broker](../advanced/wam.md) during `PublicClientApplication` creation, your app also needs to register`ms-appx-web://Microsoft.AAD.BrokerPlugin/YOUR_CLIENT_ID` as a redirect URI.
112
112
113
113
```python
114
114
result = app.acquire_token_interactive( # It automatically provides PKCE protection
Confidential client applications can securely store a secret and can authenticate both on behalf of an application as well as on behalf of a given user. With MSAL Python, developers can use [`ConfidentialClientApplication`](xref:msal.application.ConfidentialClientApplication) to access confidential client application capabilities, such as:
139
+
Confidential client applications can securely store a secret and can authenticate both on behalf of an application as well as on behalf of a given user. MSAL Python gives developers various methods to acquire tokens when developing [`ConfidentialClientApplication`](xref:msal.application.ConfidentialClientApplication).
140
140
141
141
### Acquire token for client
142
142
143
-
Acquire token as the application itself using [client credentials](/entra/identity-platform/v2-oauth2-client-creds-grant-flow), and not for a user. For example, this can be used in applications which process users in batches and not one particular user, such as syncing tools. MSAL Python provides the [`acquire_token_for_client`](/python/api/msal/msal.application.confidentialclientapplication#msal-application-confidentialclientapplication-acquire-token-for-client) method to do this. Since MSAL Python 1.23, this method will automatically look for token from cache, and only send request to Identity Provider when cache misses.
143
+
Acquire token as the application itself using [client credentials](/entra/identity-platform/v2-oauth2-client-creds-grant-flow), and not for a user. For example, this can be used in applications that process users in batches and not one particular user, such as syncing tools. MSAL Python provides the [`acquire_token_for_client`](/python/api/msal/msal.application.confidentialclientapplication#msal-application-confidentialclientapplication-acquire-token-for-client) method to do this. Since MSAL Python 1.23, this method automatically looks for token from cache, and only sends request to identity provider when cache misses.
144
144
145
145
```python
146
146
result = app.acquire_token_for_client(scopes=config["scope"])
@@ -153,9 +153,9 @@ else:
153
153
154
154
### Acquire token on behalf of
155
155
156
-
In the case of web Apps or web APIs calling another downstream Web API in the name of the user, use the [On Behalf Of flow](/entra/identity-platform/v2-oauth2-on-behalf-of-flow) to acquire a token based on a user assertion (for example, SAML, JWT). The current app is a middle-tier service which was called with a token representing an end user. The current app can use such token (also known as a user assertion) to request another token to access downstream web API, on behalf of that user.The middle-tier app has no user interaction to obtain consent. For information on gaining consent upfront for your middle-tier app, see the [documentation](/entra/identity-platform/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application).
156
+
In the case of web apps or web APIs calling another downstream Web API in the name of the user, use the [On Behalf Of flow](/entra/identity-platform/v2-oauth2-on-behalf-of-flow) to acquire a token based on a user assertion (for example, SAML, JWT). The current app is a middle-tier service that was called with a token representing an end user. The current app can use such token, also known as a user assertion, to request another token to access downstream web API on behalf of that user.The middle-tier app has no user interaction to obtain consent. For information on gaining consent upfront for your middle-tier app, see the [documentation](/entra/identity-platform/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application).
157
157
158
-
Here's an example of code that acquires an access token using the [`acquire_token_on_behalf_of`](/python/api/msal/msal.application.confidentialclientapplication#msal-application-confidentialclientapplication-acquire-token-on-behalf-of) method and the Flask framework. In this case, the downstream API is the Azure Management Subscriptions endpoint.
158
+
Here's an example of code that acquires an access token using the [`acquire_token_on_behalf_of`](/python/api/msal/msal.application.confidentialclientapplication#msal-application-confidentialclientapplication-acquire-token-on-behalf-of) method.
159
159
160
160
```python
161
161
defget(self, request): # a web service endpoint receiving a request
@@ -183,9 +183,9 @@ def get(self, request): # a web service endpoint receiving a request
183
183
184
184
## Acquire token by authorization code flow
185
185
186
-
For Web apps authenticating in the name of a user, acquire tokens through [authorization code](/entra/identity-platform/v2-oauth2-auth-code-flow) after letting the user sign-in through the authorization request URL. This is typically the mechanism used by an application which lets the user sign-in using OpenID Connect but then wants to access Web APIs for this particular user.
186
+
For web apps authenticating in the name of a user, acquire tokens through [authorization code](/entra/identity-platform/v2-oauth2-auth-code-flow) after letting the user sign-in through the authorization request URL. This is typically the mechanism used by an application that lets the user sign-in and access Web APIs for this particular user.
187
187
188
-
You'll first need to initiate auth code flow using the [`initiate_auth_code_flow`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-initiate-auth-code-flow). This method takes in among other parameters a redirect URI and state string. The value of the state parameter is also included in token response. If this value is absent, MSAL Python will automatically generate one internally. The redirect URI provided must match the redirect URI registered in the Microsoft Entra admin center. This method returns the auth code flow which is a dictionary containing auth_uri and a state. The auth_uri is the URL that the user needs to visit to sign in.
188
+
You'll first need to initiate auth code flow using the [`initiate_auth_code_flow`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-initiate-auth-code-flow). This method takes in among other parameters a redirect URI and state string. The value of the state parameter is also included in token response. If this value is absent, MSAL Python will automatically generate one internally. The redirect URI provided must match the redirect URI registered in the Microsoft Entra admin center. This method returns the auth code flow that is a dictionary containing auth_uri and a state. The auth_uri is the URL that the user needs to visit to sign in.
189
189
190
190
```python
191
191
flow = app.initiate_auth_code_flow(
@@ -200,7 +200,7 @@ session["auth_flow"] = flow
200
200
# At this point, the app should guide the user to visit the auth ur (session["auth_flow"]["auth_uri"])
201
201
```
202
202
203
-
The response from visiting the auth_uri endpoints is used in the [`acquire_token_by_auth_code_flow`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-acquire-token-by-auth-code-flow) method. The state is a unique identifier that you can use to verify the response from the authorization server. The user should consent to scopes during login.
203
+
The response from visiting the auth_uri endpoints is used in the [`acquire_token_by_auth_code_flow`](/python/api/msal/msal.application.clientapplication#msal-application-clientapplication-acquire-token-by-auth-code-flow) method. The state is a unique identifier that you can use to verify the response from the authorization server. The user should consent to scopes during sign-in.
204
204
205
205
```python
206
206
# The uth_response value from visiting the auth_uri endpoint is passed as a query string
@@ -220,4 +220,4 @@ except ValueError: # Usually caused by CSRF
220
220
221
221
Both public and confidential client applications support token caching, handled direct by MSAL Python. Applications should try to get a token from the cache first before relying on any other means. Take a look at the [recommended token acquisition pattern](/azure/active-directory/develop/scenario-desktop-acquire-token?tabs=python) to learn more.
222
222
223
-
To be able to persist the cache, the developers will need to configure the [token cache serialization](/azure/active-directory/develop/msal-python-token-cache-serialization) logic.
223
+
To be able to persist the cache, the developers need to configure the [token cache serialization](/azure/active-directory/develop/msal-python-token-cache-serialization) logic.
0 commit comments