page_type: sample languages:
This sample demonstrates a Python Django Web App calling a Python Flask Web API that is secured using Azure AD using the Microsoft Authentication Library (MSAL) for Python.
File/folder | Description |
---|---|
AppCreationScripts/ |
Scripts to automatically configure Azure AD app registrations. |
DjangoUI/ |
The web app that signs the user in |
FlaskAPI/ |
The protected resource API that performs the On-Behalf-Of flow. |
CHANGELOG.md |
List of changes to the sample. |
CONTRIBUTING.md |
Guidelines for contributing to the sample. |
LICENSE |
The license for the sample. |
- Configure VS Code for debugging Python applications
From your shell or command line:
git clone https://github.com/Azure-Samples/https://github.com/Azure-Samples/ms-identity-python-on-behalf-of.git
or download and extract the repository .zip file.
:warning: To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
DjangoUI
and FlaskAPI
) in separate VS Code instances.In the 'FlaskAPI' sub-folder, use the following command:
# start from the directory in which this sample is clone into
cd FlaskAPI
python3 -m venv venv # only required if you don't have a venv already
source venv/bin/activate
pip install -r requirements.txt
In the 'DjangoUI' sub-folder, local execution only, use the following command:
# start from the directory in which this sample is clone into
cd DjangoUI
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 are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
As a first step you'll need to:
Python Flask Web API
.app secret
),Azure Service Management
.Set
next to the Application ID URI to generate a URI that is unique for this app.api://{clientId}
) by selecting Save.access_as_user
.Access Python Flask Web API
.Allows the app to access Python Flask Web API as the signed-in user.
Access Python Flask Web API
.Allow the application to access Python Flask Web API on your behalf.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
FlaskAPI\production.env
file and make a copy in the same directory called development.env
. In this new file:CLIENT_ID
and replace the existing value with the application ID (clientId) of Python Flask Web API
app copied from the Azure portal.CLIENT_SECRET
and replace the existing value with the key you saved during the creation of Python Flask Web API
copied from the Azure portal.AUTHORITY
and replace the ReplaceWithTenantID
portion with the tenant ID value that you obtained from the portal.ISSUER
and replace the ReplaceWithTenantID
portion with the tenant ID value that you obtained from the portal.Python Django Web App
.http://localhost:8000/account/callback
.app secret
),In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
Select the Add a permission button and then:
Ensure that the My APIs tab is selected.
In the list of APIs, select the API Python Flask Web API
.
In the Delegated permissions section, select the access_as_user in the list. Use the search box if necessary.
Select the Add permissions button at the bottom.
Select the Add a permission button and then:
Ensure that the Microsoft APIs tab is selected.
In the list of APIs, select the API Microsoft Graph API
.
In the Delegated permissions section, select the openid in the list. Use the search box if necessary.
Select the Add permissions button at the bottom.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
DjangoUI\production.env
file and make a copy in the same directory called development.env
. In this new file:CLIENT_ID
and replace the existing value with the application ID (clientId) of Python Django Web App
app copied from the Azure portal.CLIENT_SECRET
and replace the existing value with the key you saved during the creation of Python Django Web App
copied from the Azure portal.DJANGO_SECRET_KEY
and replace the existing value with a Secret Key.AUTHORITY
and replace the ReplaceWithTenantID
portion with the tenant Id value that you obtained from the portal.SCOPE
and replace the Flask_API_Client_ID
portion of the existing value with with the client ID of the Flask app that you had copied from that portal in the previous section.API_SCOPE
and replace the Flask_API_Client_ID
portion of the existing value with with the client ID of the Flask app that you had copied from that portal in the previous section.For a middle tier Web API (Python Flask Web API
) to be able to call a downstream Web API, the middle tier app needs to be granted the required permissions as well.
However, since the middle tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its Azure AD registration.
This binding merges the permissions required by both the client and the middle tier Web Api and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions.
To achieve this, you need to add the Application Id of the client app, in the Manifest of the Web API in the knownClientApplications
property. Here's how:
In the Azure portal, navigate to your Python Flask Web API
app registration, and select Manifest section.
In the manifest editor, change the "knownClientApplications": []
line so that the array contains the Client ID of the client application (Python Django Web App
) as an element of the array.
For instance:
"knownClientApplications": ["your-django-app-id"],
Save the changes to the manifest.
There are two applications in this repository. You must run both of them to use the sample.
To run the FlaskAPI application, you can either use the command line or VS Code. For command line use, navigate to <project-root>/FlaskAPI
folder. Be sure your virtual environment with dependencies is activated (Prerequisites).
On Linux/OSX via the terminal:
# start from the folder in which the sample is cloned into
cd FlaskAPI
export FLASK_ENV="development"
export FLASK_APP="main.py"
flask run
On Windows:
# start from the folder in which the sample is cloned into
cd FlaskAPI
$env:FLASK_ENV="development"
$env:FLASK_APP="main.py"
flask run
On VS Code:
Python: Select Interpreter
and choose the virtual environment that you installed the project into.To run the DjangoUI application, you can either use the command line or VS Code. For command line use, navigate to <project-root>/DjangoUI
folder. Be sure your virtual environment with dependencies is activated (Prerequisites).
On Linux/OSX via the terminal:
# start from the folder in which the sample is cloned into
cd DjangoUI
export ENVIRONMENT="development"
python manage.py migrate
python manage.py runserver localhost:8000
On Windows:
# start from the folder in which the sample is cloned into
cd DjangoUI
$env:ENVIRONMENT="development"
python manage.py migrate
python manage.py runserver localhost:8000
On VS Code:
Python: Select Interpreter
and choose the virtual environment that you installed the project into.Navigate to http://localhost:8000 in your browser (Don't use use 127.0.0.1)
:information_source: Did the sample not work for you as expected? 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 a user and obtain a token for the Flask Web API, which will in turn call the Azure Management API on the user's behalf. The Django Web App first checks to see if the user has signed in before by attempting to find the user in the in-memory token cache. If the user is found, the MSAL acquire_token_silent function is first called to pull the user's access token from the token cache and then the Flask API is called. If the user is not found in the token cache, they will be redirect to account/login to sign in. Once called, the Flask API will validate the access token, using the validation logic from authorization.py, and will in turn create a new access token using the MSAL acquire_token_on_behalf_of function. This token will then be used to call the Azure Management API, subscriptions endpoint, on-behalf-of the user who initiated the request from the Django Web App.
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
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
azure-ad-b2c
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
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.