Giter Club home page Giter Club logo

ms-identity-b2c-python-flask-webapp-authentication's Introduction

page_type languages products name urlFragment description
sample
python
azure-active-directory
azure-active-directory-b2c
microsoft-identity-platform
Enable your Python Flask webapp to sign in users to your Azure Active Directory B2C tenant with the Microsoft identity platform
ms-identity-b2c-python-flask-webapp-authentication
This sample demonstrates a Python Flask webapp that signs in users with Azure Active Directory B2C (Azure AD B2C)

Enable your Python Flask webapp to sign in users to your Azure Active Directory B2C tenant with the Microsoft identity platform

Overview

This sample demonstrates a Python Flask webapp that authenticates users with Azure Active Directory B2C (Azure AD B2C) using the the Microsoft Authentication Library (MSAL) for Python.

Scenario

  1. The Web application uses MSAL for Python to sign-in a user and obtains an ID Token from Azure AD B2C.
  2. The ID Token proves that the user has successfully authenticated against an Azure AD B2C tenant.
  3. The web application protects one of its routes according to user's authentication status.
  4. The user can sign up for a new account, reset password, or edit user profile information using B2C user-flows

Overview

Contents

File/folder Description
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.

Prerequisites

Setup

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-b2c-python-flask-webapp-authentication.git

or download and extract the repository .zip file.

Step 2: Install project dependencies

  1. Navigate to the project folder
  2. Activate a Python 3 virtual environment
  3. Install project dependencies
  • In Linux/OSX via the terminal:
  cd <project-root-directory> # the folder into which you cloned this project
  python3 -m venv venv # only required to create the venv if you don't have a venv already
  source venv/bin/activate # activates the venv
  pip install -r requirements.txt
  • In Windows via PowerShell:
  cd <project-root-directory> # the folder into which you cloned this project
  python3 -m venv venv # only required to create the venv if you don't have a venv already
  Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  . .\venv\Scripts\Activate.ps1 # activates the venv
  pip install -r requirements.txt

Register the sample application with your Azure AD B2C tenant

⚠️ This sample comes with a pre-registered application for testing purposes. If you would like to use your own Azure AD B2C tenant and application, follow the steps below to register and configure the application in the Azure Portal. Otherwise, continue with the steps for Running the sample.

Expand this section to see manual steps for configuring your own tenant:

Choose the Azure AD B2C tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal.
  2. If your account is present in more than one Azure AD B2C 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 B2C tenant.

Create User Flows and Custom Policies

Please refer to Tutorial: Create user flows in Azure Active Directory B2C to create common user flows like sign up, sign in, edit profile, and password reset.

You may consider creating Custom policies in Azure Active Directory B2C as well, however, this is beyond the scope of this tutorial.

Add External Identity Providers

Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C

Register the webapp (b2c-python-flask-webapp-auth)

  1. Navigate to the Azure portal and select the Azure AD B2C service.

  2. Select the App Registrations blade on the left, then select New registration.

  3. 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 b2c-python-flask-webapp-auth.
    • Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
    • 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.
  4. Select Register to create the application.

  5. 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.

  6. Select Save to save your changes.

  7. 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.

  8. 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.

Configure the webapp (b2c-python-flask-webapp-auth) to use your app registration

Open the project in your IDE (like Visual Studio Code) to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the aad.b2c.config.json file
  2. Find the key client.client_id and replace the existing value with the application ID (clientId) of the b2c-python-flask-webapp-auth application copied from the Azure portal.
  3. Find the key client.client_credential and replace the existing value with the client secret you saved during the creation of the b2c-python-flask-webapp-auth app, in the Azure portal.
  4. Find the key client.authority and replace the the two instances of fabrikamb2c with the name of the Azure AD B2C tenant in which you registered the app.
  5. Find the key b2c.susi and set the value to the name of your sign-up/sign-in userflow policy you created in your AAD B2C tenant.
  6. Find the key b2c.profile and set the value to the name of your sign-up/sign-in userflow policy you created in your AAD B2C tenant.
  7. Find the key b2c.password and set the value to the name of your sign-up/sign-in userflow policy you created in your AAD B2C tenant.

Running the sample

  • 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 Linux/OSX via the terminal:

      export FLASK_APP=app.py
      export FLASK_ENV=development
      export FLASK_DEBUG=1
      export FLASK_RUN_CERT=adhoc
      flask run
  • On Windows:

      $env:FLASK_APP="app.py"
      $env:FLASK_ENV="development"
      $env:FLASK_DEBUG="1"
      $env:FLASK_RUN_CERT="adhoc"
      flask run
  • Alternatively, you may use python -m flask run instead of flask 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.

Experience

Explore the sample

  • 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 of your chosen identity provider.
  • 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 also have the option of editing your profile. Click the link to edit details like your display name, place of residence, and profession.
  • 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 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.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

About the code

This sample uses the Microsoft Authentication Library (MSAL) for Python to sign up and/or sign in users with an Azure AD B2C 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:

  1. A configuration object is parsed from aad.b2c.config.json

  2. A FlaskAdapter is instantiated for interfacing with the Flask app

  3. The FlaskAdapter and an Azure AD configuration object are used to instantiate IdentityWebPython.

    aad_configuration = AADConfig.parse_json('aad.b2c.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 at g.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, a 401: 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!"

Under the hood

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 Confidential Client Applications
  • The Azure AD B2C Authority concatenated with an appropriate UserFlowPolicy for sign-up-sign-in or profile-edit or password-reset.
  1. The first step of the sign-in process is to send a request to the /authorize endpoint on Azure Active Directory.

  2. 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=f'{AUTHORITY}/{B2C_SIGN_UP_SIGN_IN_USER_FLOW_POLICY}',
    )
  3. The client_instance instance is leveraged to construct a /authorize request URL with the appropriate parameters, and the browser is redirected to this URL.

  4. The user is presented with a sign-in prompt by Azure Active Directory B2C. 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.

  5. 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.
  6. 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 plaintext id_token_claims in a dictionary. It is the application's responsibility to store these tokens securely.

Deploy to Azure

Follow this guide to deploy this app to Azure App Service.

More information

Community Help and Support

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.

Contributing

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.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

ms-identity-b2c-python-flask-webapp-authentication's People

Contributors

idg-sam avatar kalyankrishna1 avatar microsoft-github-operations[bot] avatar microsoftopensource avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.