title | description | services | author | manager | ms.service | ms.workload | ms.topic | ms.date | ms.author | ms.subservice | ms.custom |
---|---|---|---|---|---|---|---|---|---|---|---|
Configure authentication in a sample Python web application by using Azure Active Directory B2C |
This article discusses how to use Azure Active Directory B2C to sign in and sign up users in a Python web application. |
active-directory-b2c |
msmimart |
celestedg |
active-directory |
identity |
reference |
06/11/2021 |
mimart |
B2C |
b2c-support |
This article uses a sample Python web application to illustrate how to add Azure Active Directory B2C (Azure AD B2C) authentication to your web applications.
OpenID Connect (OIDC) is an authentication protocol that's built on OAuth 2.0. You can use OIDC to securely sign users in to an application. This web app sample uses the Microsoft Authentication Library (MSAL) for Python. The MSAL for Python simplifies adding authentication and authorization support to Python web apps.
The sign-in flow involves the following steps:
- Users go to the web app and select Sign-in.
- The app initiates an authentication request and redirects users to Azure AD B2C.
- Users sign up or sign in, reset the password, or sign in with a social account.
- After users sign in successfully, Azure AD B2C returns an ID token to the app.
- The app exchanges the authorization code with an ID token, validates the ID token, reads the claims, and then returns a secure page to users.
[!INCLUDE active-directory-b2c-app-integration-sign-out-flow]
A computer that's running:
- Visual Studio Code or another code editor
- Python 2.7+ or 3+
[!INCLUDE active-directory-b2c-app-integration-add-user-flow]
To enable your application to sign in with Azure AD B2C, register your app in the Azure AD B2C directory. Registering your app establishes a trust relationship between the app and Azure AD B2C.
During app registration, you'll specify the Redirect URI. The redirect URI is the endpoint to which users are redirected by Azure AD B2C after they authenticate with Azure AD B2C. The app registration process generates an Application ID, also known as the client ID, that uniquely identifies your app. After your app is registered, Azure AD B2C uses both the application ID and the redirect URI to create authentication requests.
To create the web app registration, do the following:
-
Sign in to the Azure portal.
-
Select the Directory + Subscription icon in the portal toolbar, and then select the directory that contains your Azure AD B2C tenant.
-
Search for and select Azure AD B2C.
-
Select App registrations, and then select New registration.
-
Under Name, enter a name for the application (for example, webapp1).
-
Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
-
Under Redirect URI, select Web and then, in the URL box, enter
http://localhost:5000/getAToken
. -
Under Permissions, select the Grant admin consent to openid and offline access permissions checkbox.
-
Select Register.
-
Select Overview.
-
Record the Application (client) ID for later use, when you configure the web application.
[!INCLUDE active-directory-b2c-app-integration-client-secret]
Download the zip file, or clone the sample web application from GitHub.
git clone https://github.com/Azure-Samples/ms-identity-python-webapp.git
Extract the sample file to a folder where the total length of the path is 260 or fewer characters.
In the project's root directory, do the following:
- Rename the app_config.py file to app_config.py.OLD.
- Rename the app_config_b2c.py file to app_config.py.
Open the app_config.py file. This file contains information about your Azure AD B2C identity provider. Update the following app settings properties:
Key | Value |
---|---|
b2c_tenant |
The first part of your Azure AD B2C tenant name (for example, contoso ). |
CLIENT_ID |
The web API application ID from step 2.1. |
CLIENT_SECRET |
The client secret you created in step 2.2. To help increase security, consider storing it instead in an environment variable, as recommended in the comments. |
*_user_flow |
The user flows or custom policy you created in step 1. |
Your final configuration file should look like the following Python code:
import os
b2c_tenant = "contoso"
signupsignin_user_flow = "B2C_1_signupsignin"
editprofile_user_flow = "B2C_1_profileediting"
resetpassword_user_flow = "B2C_1_passwordreset"
authority_template = "https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{user_flow}"
CLIENT_ID = "11111111-1111-1111-1111-111111111111" # Application (client) ID of app registration
CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx" # Placeholder - for use ONLY during testing.
Important
As noted in the code snippet comments, we recommend that you do not store secrets in plaintext in your application code. The hard-coded variable is used in the code sample for convenience only. Consider using an environment variable or a secret store, such as an Azure key vault.
-
In your console or terminal, switch to the directory that contains the sample. For example:
cd ms-identity-python-webapp
-
Install the required packages from PyPi and run the web app on your local machine by running the following commands:
pip install -r requirements.txt flask run --host localhost --port 5000
The console window displays the port number of the locally running application:
* Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://localhost:5000/ (Press CTRL+C to quit)
-
To view the web application running on your local machine, go to http://localhost:5000.
-
Select Sign In.
-
Complete the sign-up or sign-in process.
-
After successful authentication, you'll see your display name, as shown here:
To enable your app to sign in with Azure AD B2C and call a web API, you must register two applications in the Azure AD B2C directory.
-
The web application (Python) registration you already created in Step 2. This app registration enables your app to sign in with Azure AD B2C. The app registration process generates an Application ID, also known as the client ID, that uniquely identifies your app. For example, App ID: 1.
-
The web API registration enables your app to call a protected web API. The registration exposes the web API permissions (scopes). The app registration process generates an Application ID that uniquely identifies your web API (for example, App ID: 2). Grant your app (App ID: 1) permissions to the web API scopes (App ID: 2).
The app registrations and the application architecture are described in the following diagrams:
[!INCLUDE active-directory-b2c-app-integration-call-api]
[!INCLUDE active-directory-b2c-app-integration-register-api]
[!INCLUDE active-directory-b2c-app-integration-api-scopes]
[!INCLUDE active-directory-b2c-app-integration-grant-permissions]
This sample acquires an access token with the relevant scopes, which the web app can use for a web API. To call a web API from the code, use an existing web API or create a new one. For more information, see Enable authentication in your own web API by using Azure AD B2C.
Open the app_config.py file. This file contains information about your Azure AD B2C identity provider. Update the following properties of the app settings:
Key | Value |
---|---|
ENDPOINT |
The URI of your web API (for example, https://localhost:44332/hello). |
SCOPE |
The web API scopes that you created. |
Your final configuration file should look like the following Python code:
import os
b2c_tenant = "contoso"
signupsignin_user_flow = "B2C_1_signupsignin"
editprofile_user_flow = "B2C_1_profileediting"
resetpassword_user_flow = "B2C_1_passwordreset"
authority_template = "https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{user_flow}"
CLIENT_ID = "11111111-1111-1111-1111-111111111111" # Application (client) ID of app registration
CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx" # Placeholder - for use ONLY during testing.
### More code here
# This is the API resource endpoint
ENDPOINT = 'https://localhost:44332'
SCOPE = ["https://contoso.onmicrosoft.com/api/demo.read", "https://contoso.onmicrosoft.com/api/demo.write"]
-
In your console or terminal, switch to the directory that contains the sample.
-
Stop the app. and then rerun it.
-
Select Call Microsoft Graph API.
In a production application, the app registration redirect URI is ordinarily a publicly accessible endpoint where your app is running, such as https://contoso.com/getAToken
.
You can add and modify redirect URIs in your registered applications at any time. The following restrictions apply to redirect URIs:
- The reply URL must begin with the scheme
https
. - The reply URL is case-sensitive. Its case must match the case of the URL path of your running application.