Sign in users in a sample Python Flask web application
In this article, you explore a Python Flask web app that is secured by Microsoft Entra External ID. This sample takes you through the sign-in experience for customers authenticating to a Python Flask web app. The sample web app uses the Microsoft Authentication Library for Python (MSAL Python) to handle user authentication.
Prerequisites
- Visual Studio Code or another code editor.
- Python 3+.
- An external tenant. To create one, choose from the following methods:
- (Recommended) Use the Microsoft Entra External ID extension to set up an external tenant directly in Visual Studio Code.
- Create a new external tenant in the Microsoft Entra admin center.
Register the web app
To enable your application to sign in users with Microsoft Entra, Microsoft Entra External ID must be made aware of the application you create. The app registration establishes a trust relationship between the app and Microsoft Entra. When you register an application, External ID generates a unique identifier known as an Application (client) ID, a value used to identify your app when creating authentication requests.
The following steps show you how to register your app in the Microsoft Entra admin center:
Sign in to the Microsoft Entra admin center as at least an Application Developer.
If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.
Browse to Identity >Applications > App registrations.
Select + New registration.
In the Register an application page that appears;
- Enter a meaningful application Name that is displayed to users of the app, for example ciam-client-app.
- Under Supported account types, select Accounts in this organizational directory only.
Select Register.
The application's Overview pane displays upon successful registration. Record the Application (client) ID to be used in your application source code.
To specify your app type to your app registration, follow these steps:
- Under Manage, select Authentication
- On the Platform configurations page, select Add a platform, and then select Web option.
- For the Redirect URIs enter
http://localhost:3000/getAToken
. This redirect URI is the location where the authorization server sends the access token. You can customize it to suit your use case. - Select Configure to save your changes.
Add app client secret
Create a client secret for the registered application. The application uses the client secret to prove its identity when it requests for tokens.
- From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.
- Under Manage, select Certificates & secrets.
- Select New client secret.
- In the Description box, enter a description for the client secret (for example, ciam app client secret).
- Under Expires, select a duration for which the secret is valid (per your organizations security rules), and then select Add.
- Record the secret's Value. You'll use this value for configuration in a later step. The secret value won't be displayed again, and isn't retrievable by any means, after you navigate away from the Certificates and secrets. Make sure you record it.
Grant admin consent
Once you register your application, it gets assigned the User.Read permission. However, since the tenant is an external tenant, the customer users themselves can't consent to this permission. You as the admin must consent to this permission on behalf of all the users in the tenant:
From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.
Under Manage, select API permissions.
- Select Grant admin consent for <your tenant name>, then select Yes.
- Select Refresh, then verify that Granted for <your tenant name> appears under Status for the permission.
Create a user flow
Follow these steps to create a user flow a customer can use to sign in or sign up for an application.
Sign in to the Microsoft Entra admin center as at least an External ID User Flow Administrator.
If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.
Browse to Identity > External Identities > User flows.
Select + New user flow.
On the Create page:
Enter a Name for the user flow, such as SignInSignUpSample.
In the Identity providers list, select Email Accounts. This identity provider allows users to sign-in or sign-up using their email address.
Under Email accounts, you can select one of the two options. For this tutorial, select Email with password.
- Email with password: Allows new users to sign up and sign in using an email address as the sign-in name and a password as their first factor credential.
- Email one-time-passcode: Allows new users to sign up and sign in using an email address as the sign-in name and email one-time passcode as their first factor credential. Email one-time passcode must be enabled at the tenant level (All Identity Providers > Email One-time-passcode) for this option to be available at the user flow level.
Under User attributes, choose the attributes you want to collect from the user upon sign-up. By selecting Show more, you can choose attributes and claims for Country/Region, Display Name, and Postal Code. Select OK. (Users are only prompted for attributes when they sign up for the first time.)
Select Create. The new user flow appears in the User flows list. If necessary, refresh the page.
To enable self-service password reset, use the steps in Enable self-service password reset article.
Associate the web application with the user flow
For the customer users to see the sign-up or sign-in experience when they use your app, you need to associate your app with a user flow. Although many applications can be associated with your user flow, a single application can only be associated with one user flow.
On the sidebar menu, select Identity.
Select External Identities, then User flows.
In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.
Under Use, select Applications.
Select Add application.
Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.
Choose Select.
Once you associate your app with a user flow, you can test your user flow by simulating a user’s sign-up or sign-in experience with your application from within the Microsoft Entra admin center. To do so, use the steps in Test your sign-up and sign-in user flow.
Clone or download sample web application
To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.
To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:
git clone https://github.com/Azure-Samples/ms-identity-docs-code-python.git
Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.
Install project dependencies
Open a console window, and change to the directory that contains the Flask sample web app:
cd flask-web-app
Set up virtual environment
py -m venv .venv .venv\scripts\activate
Run the following commands to install app dependencies:
python3 -m pip install -r requirements.txt
Configure the sample web app
Open your project files on Visual Studio Code or the editor you're using.
Create an .env file in the root folder of the project using .env.sample file as a guide.
In your .env file, provide the following environment variables:
CLIENT_ID
which is the Application (client) ID of the app you registered earlier.CLIENT_SECRET
which is the app secret value you copied earlier.AUTHORITY
which is the URL that identifies a token authority. It should be of the format https://{subdomain}.ciamlogin.com/{subdomain}.onmicrosoft.com. Replace subdomain with the Directory (tenant) subdomain. For example, if your tenant primary domain iscontoso.onmicrosoft.com
, usecontoso
. If you don't have your tenant subdomain, learn how to read your tenant details.
Confirm that the redirect URI is well configured. The redirect URI you registered earlier should match your configuration. This sample by default sets the redirect URI path to
/getAToken
. This is configured in the app_config.py file as REDIRECT_PATH.
Run and test sample web app
Run the app to see the sign-in experience at play.
Note
This sample uses the Python identity third-party library. The library isn't officially maintained by Microsoft but is recommended for your use. This library makes it easier to add authentication to your web app as it abstracts a lot of the MSAL Python details.
In your terminal, run the following command:
python3 -m flask run --debug --host=localhost --port=3000
You can use the port of your choice. This should be similar to the port of the redirect URI you registered earlier.
Open your browser, then go to
http://localhost:3000
. You should see the page similar to the following screenshot:After the page completes loading, select Sign In link. You're prompted to sign in.
On the sign-in page, type your Email address, select Next, type your Password, then select Sign in. If you don't have an account, select No account? Create one link, which starts the sign-up flow.
If you choose the sign-up option, you'll go through the sign-uo flow. Fill in your email, one-time passcode, new password and more account details to complete the whole sign-up flow.
After you sign in or sign up, you're redirected back to the web app. You'll see a page that looks similar to the following screenshot:
Select Logout to sign the user out of the web app or select Call a downstream API to make a call to a Microsoft Graph endpoint.
How it works
When users select the Sign in link, the app initiates an authentication request and redirects users to Microsoft Entra External ID. A user then signs in or signs up page on the page that appears. After providing in the required credentials and consenting to required scopes, Microsoft Entra External ID redirects the user back to the web app with an authorization code. The web app then uses this authorization code to acquire a token from Microsoft Entra External ID.
When the users select the Logout link, the app clears its session, the redirect the user to Microsoft Entra External ID sign-out endpoint to notify it that the user has signed out. The user is then redirected back to the web app.