Retrieve User Claims in Python Flask App for Azure Container Apps After Authentication
Published Mar 15 2024 06:08 AM 1,680 Views
Microsoft

The Token Store feature is currently supported in preview mode and can be enabled via the Azure CLI using the command az containerapp auth update with the --token-store boolean flag.

 

At the moment, the implementation only supports Blob Storage, which can be configured using the --sas-url-secret and --sas-url-secret-name parameters. More details on enabling the token store will be available soon in the public documentation.

 

However, I am going to talk about in this article that even without enabling the token store, it is still possible to retrieve user claims in the application code for Azure Container Apps after authentication, as described in this documentation: Access User Claims in Application Code. The claims are injected into the request headers, making them accessible whether from an authenticated end user or a client application.

  • X-MS-CLIENT-PRINCIPAL-NAME
  • X-MS-CLIENT-PRINCIPAL-ID

I would like to share a simple sample in Python Flask app to demonstrate it. The sample code is downloaded from here following this doc.

Get the Sample Code

git clone https://github.com/Azure-Samples/msdocs-python-flask-webapp-quickstart.git

Add Claims div in the index.html Page

<label for="principal_name" class="form-label fw-bold fs-5">X-MS-CLIENT-PRINCIPAL-NAME:</label>
<div class="d-grid gap-2 d-sm-flex justify-content-sm-center align-items-center my-1">
  <p class="form-control-static">{{ principal_name }}</p>
</div>

<label for="principal_id" class="form-label fw-bold fs-5">X-MS-CLIENT-PRINCIPAL-ID:</label>
<div class="d-grid gap-2 d-sm-flex justify-content-sm-center align-items-center my-1">
  <p class="form-control-static">{{ principal_id }}</p>
</div>

Retrieve the Claims from Request Headers

def index():
   print('Request for index page received')
   #return render_template('index.html')

   # Get the request headers
   headers = request.headers
   # Get the values of the desired headers
   principal_name = headers.get('X-MS-CLIENT-PRINCIPAL-NAME')
   principal_id = headers.get('X-MS-CLIENT-PRINCIPAL-ID')
   return render_template('index.html', principal_name=principal_name, principal_id=principal_id)

Deploy Web App to Azure

After deploying the app to Azure Container Apps and enabling the built-in Authentication with Microsoft Identity, upon successful authentication, you will be able to view the user claims on the index page.

result.png

 

Co-Authors
Version history
Last update:
‎Mar 14 2024 11:08 PM
Updated by: