page_type | languages | products | name | urlFragment | description | ||||
---|---|---|---|---|---|---|---|---|---|
sample |
|
|
A Python Flask Webapp for signing-in users in your Azure AD tenant with the Microsoft Identity platform |
ms-identity-python-flask-webapp-authentication |
This sample demonstrates a Python Flask webapp that signs in users in your tenant using Azure Active Directory |
A Python Flask Webapp for signing in users in your organization with the Microsoft identity platform
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Register the sample application(s) with your Azure Active Directory tenant
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
- Code of Conduct
This sample demonstrates a Python Flask web app signing-in users in your own tenant using the Microsoft Authentication Library (MSAL) for Python with Azure Active Directory.
- This sample shows how to build a Flask Web app that uses Microsoft Authentication Library (MSAL) for Python leveraging the OpenID Connect protocol to sign in users in an organization's Azure Active Directory tenant.
- Users can only sign in with their work and school accounts in their own Azure AD tenant.
- Once the user has signed in with Azure AD, the ID token is used by the webapp to authenticate, maintaining the user's signed-in status in a session variable.
File/folder | Description |
---|---|
AppCreationScripts/ |
Folder contains scripts to automatically configure Azure AD app registrations |
authenticate_users_in_my_tenant.py |
The sample app code. |
auth_endpoints.py |
The auth related endpoints code. |
CHANGELOG.md |
List of changes to the sample. |
CONTRIBUTING.md |
Guidelines for contributing to the sample. |
LICENSE |
The license for the sample. |
- Python 3
- A virtual environment to install packages from requirements.txt
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. Therefore, if you signed in to the Azure portal with a personal account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-python-flask-webapp-authentication.git
or download and extract the repository .zip file.
- navigate to the project folder
- activate a Python 3 virtual environment
- install project dependencies
- In Linux/OSX via the terminal:
cd project-root-directory
python3 -m venv venv # only required if you don't have a venv already
source venv/bin/activate
pip install -r requirements.txt
- In Windows via PowerShell:
cd project-root-directory
python3 -m venv venv # only required if you don't have a venv already
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
. .\venv\Scripts\Activate.ps1
pip install -r requirements.txt
There is one project in this sample. To register it, you can:
- either follow the step Choose the Azure AD tenant where you want to create your applications below
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
Follow the steps below to manually walk through the steps to register and configure the applications in the Azure portal.
As a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD tenant..
-
Navigate to the Microsoft identity platform for developers App registrations page.
-
Select New registration.
-
In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
WebApp_Python_Flask_Authentication_MyOrg
. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI:
https://127.0.0.1:5000/auth/redirect
.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
-
Select Register to create the application.
-
In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
-
Select Save to save your changes.
-
In the app's registration screen, click on the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
-
In the Client secrets section, click on New client secret:
- Type a key description (for instance
app secret
), - Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security concerns.
- The generated key value will be displayed when you click the Add button. Copy the generated value for use in the steps later.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
Open the project in your IDE to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
config.py
file - Find the app key
default-value-enter-your-tenant-id-here
and replace the existing value with your Azure AD tenant ID. - Find the app key
default-value-enter-your-client-id-here
and replace the existing value with the application ID (clientId) of theWebApp_Python_Flask_Authentication_MyOrg
application copied from the Azure portal. - Find the app key
default-value-enter-your-client-secret-here
and replace the existing value with the key you saved during the creation of theWebApp_Python_Flask_Authentication_MyOrg
app, in the Azure portal.
- To run the sample, open a terminal window. Navigate to the root of the project. Be sure your virtual environment with dependencies is activated (Prerequisites).
- In Linux/OSX via the terminal:
export FLASK_APP=authenticate_users_in_my_tenant.py export FLASK_ENV=development export FLASK_DEBUG=1 export FLASK_RUN_CERT=adhoc flask run
- In Windows via PowerShell:
set FLASK_APP=authenticate_users_in_my_tenant.py set FLASK_ENV=development set FLASK_DEBUG=1 set FLASK_RUN_CERT=adhoc flask run
- Alternatively, you may use
python -m flask run
instead offlask run
- Navigate to https://127.0.0.1:5000 in your browser
- Note the signed-in or signed-out status displayed at the center of the screen.
- Click the context-sensitive button at the top right (it will read
Sign In
on first run) - Follow the instructions on the next page to sign in with an account in the Azure AD tenant.
- Note the context-sensitive button now says
Sign out
and displays your username to its left. - The middle of the screen now has an option to click for ID Token Details: click it to see some of the ID token's decoded claims.
- You can also use the button on the top right to sign out.
- After signing out, click this link to the token details page to observe how the app displays a
401: unauthorized
error instead of the ID token claims.
ℹ️ Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.
This sample shows how to use Microsoft Authentication Library (MSAL) for Python to sign in users from your Azure AD tenant.
-
A ConfidentialClientApplication object is instantiated in the auth_endpoints.py file. The following parameters need to be provided upon instantiation:
- The Client ID of the app
- The Azure AD Authority (which, in this sample, includes the Tenant ID of the AAD application).
- The Client Secret, which is a requirement for Confidential Client Applications
-
In this sample, these values are read from the flask configuration object, which receives them from the config.py file.
msal_instance = msal.ConfidentialClientApplication(
config.get('CLIENT_ID'),
client_credential=config.get('CLIENT_SECRET'),
authority=config.get('AUTHORITY'),
token_cache=None # we don't need a serializable token cache for this project. In-memory token cache will suffice.
)
- The first step of the sign-in process is to send a request to the /authorize endpoint on Azure Active Directory. Our MSAL(Python) ConfidentialClientApplication instance is leveraged to construct an authorization request URL, and our app redirects the browser to this URL.
- The user is presented with a sign-in prompt by Azure Active Directory. If the sign-in attempt is successful, the user's browser is redirected to our app's redirect endpoint. A valid request to this endpoint will contain an authorization code.
- Our ConfidentialClientApplication instance then exchanges this authorization code for an ID Token and Access Token from Azure Active Directory.
token_acquisition_result = msal_instance.acquire_token_by_authorization_code(authorization_code, config.get('SCOPES'))
MSAL Python:
- Downloads the Azure AD metadata, including signing keys, and finds the issuer name for the tenant.
- Processes Azure AD responses by validating the signature and issuer in the ID and/or Access tokens.
- Parses the ID Token claims into plaintext.
The result is then put into a server-side session, in the following properties:
session['msal_token_result']=token_acquisition_result
session['msal_authenticated']=True
id_token_claims=token_acquisition_result.get('id_token_claims', {})
session['msal_id_token_claims'] = id_token_claims
session['msal_username'] = id_token_claims.get('name', None)
-
Microsoft identity platform (Azure Active Directory for developers)
-
Quickstart: Register an application with the Microsoft identity platform (Preview)
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory
ms-identity
adal
msal
].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.