Skip to content

OAuth with Python and Microsoft Entra ID

This documentation provides a step-by-step guide for using Microsoft Entra ID as an identity provider for a Python web application. Leveraging Microsoft’s robust identity management platform enhances security and simplifies users’ login processes.

What is Entra ID

Microsoft Entra ID is a comprehensive cloud identity and access management solution. It provides a robust set of capabilities to manage users and groups and secure access to applications.

This service is used by Azure, but both services are independent, and Microsoft Entra ID can be used independently of Azure.

Last point, Microsoft Entra ID is a service provided by Microsoft Entra which is a broader suite of identity and access management solutions offered by Microsoft.

Creates the Entra Application

  1. Navigate to the Entra Portal and Sign IN
  1. Create a New Application
  • In the left-hand navigation pane, select “Identity” then “Applications” and click on “App registrations”.
  • Click on “New registration”.
  1. Configure the Application
  • Enter the name of the application.
  • Choose the supported account types. For most use cases, select “Accounts in this organizational directory only”.
  • Under Redirect URI, select “Web” and enter the URL http://localhost:5000/callback where your application will handle sign-in responses.
  • Click “Register”.
  1. Copy the Application (client) ID and the Tenant ID
  • You will be redirected to the application’s overview page after registration.
  • Note down the Application (client) ID and the Tenant ID as you will need them later.
  1. Generate a Client Secret
  • In the left-hand menu, select “Certificates & secrets”.
  • Under Client secrets, click “New client secret”.
  • Add a description and choose an expiration period.
  • Click “Add” and note down the Value of the client secret.

Creates the Entra Application

Creates the Python Web Application

It is time to create the Python Web Application using the previously created Microsoft Entra ID Application.

Prerequisites

Before you begin, ensure you have Python installed on your machine. You will also need to install the following packages:

  • Flask: A lightweight WSGI web application framework.
  • Authlib: A library for building OAuth and OpenID Connect clients and servers.
  • requests: A library for HTTP requests used by Authlib.

You can install these packages using pip:

Terminal window
pip install Flask Authlib requests

Officials documentation:

Code

Here the Python Web Application without the credentials previously created.

$ cat app.py
from flask import Flask
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
# Secret key for the user session.
app.secret_key = 'randomkey'
# Application credentials.
CLIENT_ID = "<CLIENT-ID>"
CLIENT_SECRET = "<CLIENT-SECRET>"
# Endpoint for the connection are based on the tenant ID.
TENANT_ID = "<TENANT-ID>"
ACCESSS_TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
AUTHORIZE_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize"
# Connection to the Microsoft Entra ID API using the application previously created.
oauth = OAuth()
oauth.init_app(app)
oauth.register(
    name='entra',
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    access_token_url=ACCESSS_TOKEN_URL,
    authorize_url=AUTHORIZE_URL,
    client_kwargs={
        'scope': 'User.Read'
},
)
@app.route('/')
def login():
    """
Route to start the login process.
"""
redirect_url = "http://localhost:5000/callback"
    return oauth.entra.authorize_redirect(redirect_url)
@app.route("/callback")
def callback():
    """
Route called by Microsoft Entra ID after user login.
Retrieve access token to retrieve user profile then return it.
"""
resp = oauth.entra.authorize_access_token()
resp = oauth.entra.get('https://graph.microsoft.com/v1.0/me')
resp.raise_for_status()
profile = resp.json()
    return profile

Running this file with the command flask run starts a webserver available at http://localhost:5000 running the OAuth workflow and retrieving user information.

Web application demo

Note on Security and Error Handling

  • Security Considerations: Ensure that sensitive information such as CLIENT_SECRET is not hardcoded in the source code. Use environment variables or a secure vault to store these credentials.
  • Error Handling: The current implementation lacks error handling for visibility purposes.

Conclusion

This integration enhances application security and simplifies user login by leveraging a robust identity management platform.