page_type | languages | products | name | urlFragment | description | |||||
---|---|---|---|---|---|---|---|---|---|---|
sample |
|
|
Enable your Python Flask webapp to sign in users to your Azure Active Directory tenant with the Microsoft identity platform |
ms-identity-python-flask-webapp-authentication |
This sample demonstrates a Python Flask webapp that signs in users to your Azure AD tenant with the Microsoft identity platform |
Enable your Python Flask webapp to sign in users to your Azure Active Directory tenant with the Microsoft identity platform
- Enable your Python Flask webapp to sign in users to your Azure Active Directory tenant 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
- We'd love your feedback!
- About the code
- Next Steps or Deploy to Azure
- Community Help and Support
- Contributing
- Code of Conduct
- More information
This sample demonstrates a Python Flask web app that signs in users to your Azure Active Directory tenant using the Microsoft Authentication Library (MSAL) for Python.
- This Web application uses the MSAL for Python to sign in users to their own Azure AD tenant and obtains an ID Token from Azure AD.
- The ID Token proves that a user has successfully authenticated with this tenant.
- The web application protects one of its routes according to user's authentication status.
File/folder | Description |
---|---|
AppCreationScripts/ |
Scripts to automatically configure Azure AD app registrations. |
app.py |
The sample app 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.8
- A virtual environment to install packages listed in 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 own Azure AD tenant. This sample will not work with a personal Microsoft account. If have not yet created a user account in your AD tenant yet, you should do so before proceeding.
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> # the folder into which you cloned the code
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> # the folder into which you cloned the code
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 the app on the portal, you can:
- either follow manual configuration steps 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 PowerShell 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.
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
python-flask-webapp-auth-my-tenant
. - 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
aad.config.json
file - Find the string
{enter-your-tenant-id-here}
and replace the existing value with your Azure AD tenant ID. - Find the string
{enter-your-client-id-here}
and replace the existing value with the application ID (clientId) of thepython-flask-webapp-auth-my-tenant
application copied from the Azure portal. - Find the string
{enter-your-client-secret-here}
and replace the existing value with the key you saved during the creation of thepython-flask-webapp-auth-my-tenant
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).
-
On OSX via the terminal with trusted certs:
# start from the folder in which the sample code is cloned into cd ./ssl source generate-local-cert.sh source trust-local-cert-on-macos.sh cd ../ # back to folder in which the sample code is cloned into source run.flask.dev.certs.sh
-
Or in Linux/OSX via terminal with ad-hoc certs:
# start from the folder in which the sample is cloned into source run.flask.dev.sh
-
On Windows:
# start from the folder in which the sample is cloned into . .\run.flask.dev.ps1
-
Alternatively, you may use
python -m flask run
instead offlask run
-
Navigate to https://127.0.0.1:5000 in your browser.
You might run into an invalid certificate error on your browser as we are using self-signed certificates for
https
. If you do, you can ignore that error while running this sample locally.
- 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 the link to
ID Token Details
to observe that the app displays a401: unauthorized
error instead of the ID token claims when the user is not authorized.
ℹ️ 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.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
This sample uses the Microsoft Authentication Library (MSAL) for Python to sign in users within your Azure AD tenant. It leverages the IdentityWebPython class found in the Microsoft Identity Python Samples Common repository to allow for quick app setup.
In app.py
's def create_app
method:
-
A configuration object is parsed from aad.config.json
-
A FlaskAdapter is instantiated for interfacing with the Flask app
-
The FlaskAdapter and an Azure AD configuration object are used to instantiate IdentityWebPython.
aad_configuration = AADConfig.parse_json('aad.config.json') adapter = FlaskContextAdapter(app) ms_identity_web = IdentityWebPython(aad_configuration, adapter)
-
These three lines of code automatically hook up all necessary endpoints for the authentication process into your Flask app under a route prefix (
/auth
by default). For example, the redirect endpoint is found at/auth/redirect
. -
When a user navigates to
/auth/sign_in
and completes a sign-in attempt, the resulting identity data is put into the session, which can be accessed through the flask global g object atg.identity_context_data
. -
When an endpoint is decorated with
@ms_identity_web.login_required
, the application only allows requests to the endpoint from authenticated (signed-in) users. If the user is not signed-in, a401: unauthorized
error is thrown, and the browser is redirected to the 401 handler.@app.route('/a_protected_route') @ms_identity_web.login_required def a_protected_route(): return "if you can see this, you're signed in!"
In this sample, much of the required MSAL for Python configurations are automatically setup using utilities found in Microsoft Identity Python Samples Common. For a more direct, hands-on demonstration of the sign-in process without this abstraction, please see the code within this Python Webapp sample.
At a minimum, following parameters need to be provided to the MSAL for Python library:
- The Client ID of the app
- The Client Credential, which is a requirement for a Web (Confidential Client) Application.
- The Azure AD Authority, which includes the Tenant ID of the AAD application in this sample's scenario.
-
The first step of the sign-in process is to send a request to the
/authorize
endpoint on Azure Active Directory. -
An MSAL for Python ConfidentialClientApplication instance is created by ms_identity_web, like so:
client_instance = msal.ConfidentialClientApplication( client_id=CLIENT_ID, client_credential=CLIENT_CREDENTIAL, authority=AUTHORITY, )
-
The
client_instance
instance is leveraged to construct a/authorize
request URL with the appropriate parameters, and the browser is redirected 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 back to this app's
/redirect
endpoint. A successful request to this endpoint will contain an authorization code. -
The
client_instance
is used to exchange this authorization code for an ID Token and Access Token from Azure Active Directory.token_acquisition_result = client_instance.acquire_token_by_authorization_code(authorization_code, SCOPES) # this sends the authorization code to Azure AD's `/token` endpoint to request a token.
-
If the request is successful, MSAL for Python validates the signature and nonce of the incoming token. If these checks succeed, it returns the resulting
id_token
,access_token
and plaintextid_token_claims
in a dictionary. It is the application's responsibility to store these tokens securely.
As next steps, we can now either get an Access Token for the users we signed-in in this tutorial, or we can proceed to deploy this app to the Azure App Service.
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.