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
title: Overview of the Microsoft Authentication Library (MSAL) for Python
3
3
description: Get started with the Microsoft Authentication Library for Python to sign in users or apps with Microsoft identities."
4
-
author: Dickson-Mwendia
4
+
author: SHERMANOUKO
5
5
manager: CelesteDG
6
6
7
7
ms.service: msal
8
8
ms.subservice: msal-python
9
9
ms.topic: conceptual
10
-
ms.date: 02/07/2024
11
-
ms.author: dmwendia
12
-
ms.reviewer: shermanouko, rayluo
10
+
ms.date: 02/29/2024
11
+
ms.author: shermanouko
12
+
ms.reviewer: dmwendia, rayluo
13
13
---
14
14
15
15
# Microsoft Authentication Library (MSAL) for Python
16
16
17
-
The Microsoft Authentication Library (MSAL) for Python library enables you to sign in users or apps with Microsoft identities ([Microsoft Entra ID](https://azure.microsoft.com/services/active-directory/), [Microsoft Accounts](https://account.microsoft.com), and [Azure AD B2C](https://azure.microsoft.com/services/active-directory-b2c/) accounts). Using MSAL Python, you can acquire tokens from Microsoft Entra ID to call protected web APIs such as [Microsoft Graph](https://graph.microsoft.io/), other Microsoft APIs, or your own APIs.
18
-
19
-
17
+
The Microsoft Authentication Library (MSAL) for Python library enables you to sign in users or apps with Microsoft identities. These identities include work and school accounts, personal Microsoft accounts, social accounts, customer accounts, and so on. Using MSAL Python, you can acquire tokens from Microsoft Entra to call protected web APIs such as [Microsoft Graph](https://graph.microsoft.io/), other Microsoft APIs, or your own APIs. MSAL Python supports various application types, including public client applications (desktop and mobile) and confidential client applications (web apps, web APIs, and daemon applications).
20
18
21
19
## Prerequisites
22
20
@@ -31,22 +29,36 @@ Install the MSAL for Python package. You can find MSAL Python on [PyPI](https://
31
29
pip install msal
32
30
```
33
31
34
-
## Setting up
32
+
## Identity concepts
33
+
34
+
MSAL Python is part of the [Microsoft identity platform](/entra/identity-platform/v2-overview) ecosystem. It's important to familiarize yourself with the following concepts to effectively use MSAL Python to protect your applications and APIs:
35
+
36
+
-[Identity and access management](/entra/fundamentals/identity-fundamental-concepts)
37
+
-[Authentication and authorization](/entra/identity-platform/authentication-vs-authorization)
38
+
-[OAuth 2.0 and OpenID Connect (OIDC) in the Microsoft identity platform](/entra/identity-platform/v2-protocols)
39
+
-[Confidential and public client accounts in the Microsoft identity platform](/entra/identity-platform/msal-client-applications)
Before using MSAL Python, make sure to [register your application](/azure/active-directory/develop/quickstart-v2-register-an-app) with the Microsoft identity platform. You will need to take note of your **client ID** and **tenant ID**.
44
+
To use MSAL Python, register an application with the Microsoft identity platform. You'll need an Azure account with an active subscription. [Create a free account](https://signup.azure.com/) if you don't have one. You can register your app in a [customer tenant](/entra/external-id/customers/quickstart-tenant-setup) or [workforce tenant](/entra/identity-platform/scenario-web-app-sign-user-app-registration?tabs=python).
37
45
38
-
>[!IMPORTANT]
39
-
>When registering the application, make sure that you set up **redirect URLs** within the **Authentication** blade. Redirect URLs vary depending on the target platform.
40
-
>
41
-
>
42
-
>
43
-
>For desktop and mobile applications, make sure you add `http://localhost` as redirect URL if you do not rely on authentication brokers.
46
+
Applications can use MSAL Python to acquire tokens for accessing protected APIs. Different app types acquire tokens using different auth flows. The supported app types include desktop applications, web applications, web APIs, and applications running on devices that don't have a browser (such as IoT devices).
47
+
48
+
In MSAL Python, applications are categorized as follows:
49
+
50
+
-[Public client applications](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1) (desktop and mobile). These types of apps cannot store app secrets securely.
51
+
-[Confidential client applications](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1) (web apps, web APIs, and daemon applications). These type of apps securely store a secret registered with Microsoft Entra ID.
52
+
53
+
For more information, see the documentation on [public client and confidential client apps](/entra/identity-platform/msal-client-applications) and the [different app types and their auth flows](/entra/identity-platform/authentication-flows-app-scenarios) in the Microsoft identity platform.
54
+
55
+
After determining whether your application is a public or confidential client application, you can use MSAL Python to acquire tokens for different scenarios.
44
56
45
57
## Basic usage
46
58
47
59
Acquiring tokens with MSAL Python follows a three-step pattern. There will be some variations for different flows. If you would like to see them in action, download our [samples](https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample).
48
60
49
-
1. MSAL relies on a clean separation between [public client and confidential client applications](https://tools.ietf.org/html/rfc6749#section-2.1). Therefore, create either a [`PublicClientApplication`](xref:msal.application.PublicClientApplication) or a [`ConfidentialClientApplication`](xref:msal.application.ConfidentialClientApplication) instance and reuse it during the lifecycle of your application. For example, for a public client application, the initalization code might look like this:
61
+
1. MSAL relies on a clean separation between public client and confidential client applications. Therefore, create either a [*PublicClientApplication*](xref:msal.application.PublicClientApplication) or a [*ConfidentialClientApplication*](xref:msal.application.ConfidentialClientApplication) instance and reuse it during the lifecycle of your application. For example, for a public client application, the initialization code might look like this:
50
62
51
63
```python
52
64
from msal import PublicClientApplication
@@ -56,33 +68,29 @@ Acquiring tokens with MSAL Python follows a three-step pattern. There will be so
>The authority isset to `/common` to allow sign ins with both organizaiton and personal Microsoft accounts. You can change it to `/organizations` to only allow sign ins with work and school accounts, `/consumers` to only allow personal Microsoft accounts, orwith`/YOUR_TENANT_ID` to only allow sign ins from work and school accounts associated with your tenant.
71
+
The authority value varies depending on the type of accounts you are signing-inand the kind of tenant your app is registered in. For example, to sign-in both work and personal Microsoft accounts provisioned in workforce tenants (Microsoft Entra ID) you would use `https://login.microsoftonline.com/common`. For customer accounts provisioned in customer tenants, your authority will take a form like `https://<subdomain>.ciamlogin.com`. For more information, see [token issuer documentation](/entra/identity-platform/access-tokens#validate-the-issuer).
61
72
62
-
Instantiate a variable to hold the authentication result:
73
+
1. Try and obtain the tokens from the cache first. The API model inMSAL provides you explicit control on how to utilize the token cache. While the caching part is technically optional, we highly recommend you to use it in your application. Using the cache you can ensure that you're not making any extra API calls and handle the token refresh automatically.
63
74
64
75
```python
65
-
result =None# It is just an initial value. Please follow instructions below.
76
+
# initialize result variable to hole the token response
77
+
result=None
78
+
79
+
# We now check the cache to see
80
+
# whether we already have some accounts that the end user already used to sign in before.
81
+
accounts= app.get_accounts()
82
+
if accounts:
83
+
# If so, you could then somehow display these accounts and let end user choose
84
+
print("Pick the account you want to use to proceed:")
85
+
for a in accounts:
86
+
print(a["username"])
87
+
# Assuming the end user chose this one
88
+
chosen= accounts[0]
89
+
# Now let's try to find a token in cache for this account
2. Try and obtain the tokens from the cache first. The API model inMSAL provides you explicit control on how to utilize the token cache. While the caching part is technically optional, we highly recommend you to use it in your application. Using the cache you can ensure that you're not making any extra API calls and handle the token refresh automatically.
69
-
70
-
```python
71
-
# We now check the cache to see
72
-
# whether we already have some accounts that the end user already used to sign in before.
73
-
accounts = app.get_accounts()
74
-
if accounts:
75
-
# If so, you could then somehow display these accounts and let end user choose
76
-
print("Pick the account you want to use to proceed:")
77
-
for a in accounts:
78
-
print(a["username"])
79
-
# Assuming the end user chose this one
80
-
chosen = accounts[0]
81
-
# Now let's try to find a token in cache for this account
82
-
result = app.acquire_token_silent(["User.Read"], account=chosen)
83
-
```
84
-
85
-
3. If there is no suitable token in the cache or you've chosen to skip the previous step, send a request to Microsoft Entra ID to get a token. There are different methods based on your client type and scenario, but for the purposes of the example we're showing how to use [`acquire_token_interactive`](xref:msal.application.PublicClientApplication.acquire_token_interactive) which will prompt the user to provide their credentials.
93
+
1. If there's no suitable token in the cache or you chose to skip the previous step, send a request to Microsoft Entra ID to get a token. There are different methods based on your client type and scenario, but for the purposes of the example we're showing how to use [`acquire_token_interactive`](xref:msal.application.PublicClientApplication.acquire_token_interactive), which prompts the user to provide their credentials.
86
94
87
95
```python
88
96
ifnot result:
@@ -96,41 +104,26 @@ Acquiring tokens with MSAL Python follows a three-step pattern. There will be so
96
104
print(result.get("correlation_id")) # You may need this when reporting a bug
97
105
```
98
106
99
-
4. Save the code into a Python file locally, such as `msaltest.py`.
100
-
5. Run the code by executing `python .\msalpytest.py`.
101
-
102
-
>[!NOTE]
103
-
>You can also download runnable samples from the [library repository](https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/1.22.0/sample/interactive_sample.py).
104
-
105
-
If the application was configured correctly, you should see a web browser window appear asking the user to sign in.
106
-
107
-

108
-
109
-
Once the authentication is completed and you closed the browser, you should be able to see the access token printed in the terminal.
110
-
111
-
## Usage scenarios
112
-
113
-
MSAL Python can be used by applications to acquire tokens to access protected APIs. Tokens can be acquired by different **application types**: desktop applications, web applications, web APIs, and applications running on devices that don't have a browser (such as IoT devices). In MSAL Python, applications are categorized as follows:
107
+
1. Save the code into a Python file locally, such as`msaltest.py`.
108
+
1. Run the code by executing `python .\msalpytest.py`. The following visual shows the sign-in experience for this example.
114
109
115
-
-**Public client applications (desktop and mobile)**. These types of apps cannot store app secrets securely.
116
-
-**Confidential client applications (web apps, web APIs, and daemon applications)**. These type of apps securely store a secret registered with Microsoft Entra ID.
110
+

117
111
118
-
Learn more about instantiating and configuring the above in the [Client applications](./getting-started/client-applications.md) topic.
112
+
1. Once the authentication is completed andyou closed the browser, you should be able to see the access token printed in the terminal.
119
113
120
-
MSAL Python supports acquiring tokens either in the name of a user or in the name of the application itself (without a user). In the latter case, a confidential client application must be used.
114
+
## Samples
121
115
122
-
MSAL Python can be used in applications running on different operating systems (Windows, Linux, macOS).
116
+
There are several samples you can use to get started withMSAL Python.
123
117
124
-
Key scenarios supported by MSAL Python:
118
+
- Samples from the [library repository](https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/1.22.0/sample). These samples demonstrate the different configurations and auth flows that you implement using MSAL Python.
119
+
- A single repository with [samples used in our documentation](https://github.com/Azure-Samples/ms-identity-docs-code-python). These samples have supporting documentation to help you build and replicate them from scratch.
125
120
126
-
-[Web application that signs in users](/azure/active-directory/develop/scenario-web-app-sign-user-overview)
127
-
-[Web Application signing in a user and calling a Web API in the name of the user](/azure/active-directory/develop/scenario-web-app-call-api-overview) (note that MSAL only helps the web application to sign in and obtain tokens. To [protect a web API](/azure/active-directory/develop/scenario-protected-web-api-overview), you will need other libraries).
128
-
-[Desktop application calling a Web API in the name of the signed-in user](/azure/active-directory/develop/scenario-desktop-overview)
129
-
-[Desktop/service daemon application calling Web API without a user](/azure/active-directory/develop/scenario-daemon-overview)
130
-
-[Application without a browser, or IOT application calling an API in the name of the user](/azure/active-directory/develop/scenario-desktop-acquire-token?tabs=python#command-line-tool-without-web-browser)
121
+
## References
131
122
132
-
Can't find the scenario you are looking for? Check out the [supported scenarios and platforms](/azure/active-directory/develop/authentication-flows-app-scenarios#scenarios-and-supported-platforms-and-languages) across MSAL libraries.
123
+
-MSAL Python library repository on [GitHub](https://github.com/AzureAD/microsoft-authentication-library-for-python)
124
+
-MSAL Python releases on [GitHub](https://github.com/AzureAD/microsoft-authentication-library-for-python/releases).
133
125
134
-
## Releases
126
+
## See also
135
127
136
-
Refer to [MSAL Python releases on GitHub](https://github.com/AzureAD/microsoft-authentication-library-for-python/releases).
128
+
- [Instantiate your application](./getting-started/client-applications.md) using MSAL Python
129
+
- [Acquire tokens](./getting-started/acquiring-tokens.md) using MSAL Python
0 commit comments