Blog Post

IIS Support Blog
2 MIN READ

Fetching Windows Auth User ID Issue in Python Flask Application on IIS with HttpPlatformHandler

PradeepSharma's avatar
PradeepSharma
Icon for Microsoft rankMicrosoft
Aug 29, 2024

Problem : Deploying Python Flask applications on IIS can be a smooth process, but occasionally, issues arise that require careful troubleshooting. One such issue involves the failure of a Flask application to retrieve the Windows Authentication user ID when using the HttpPlatformHandler. Please note that retrieving the user details was successful using WFastCGI but not with HttpPlatformHandler. Let’s see how we can fetch the user details in such scenario.

 

Few Pointers :

Move to HttpPlateFormHandlers form WFastCGI: WFastCGI is no longer maintained. Refer to this.

Configure Python web apps for IIS - Visual Studio (Windows) | Microsoft Learn

 

 

Configuration Adjustment:

A key step was enabling the ForwardWindowsAuthToken option in the HttpPlatformHandler configuration. This setting forwards the Windows Authentication token to the application, allowing it to be accessed and processed within the code.

 

Code Implementation:

After adjusting the configuration, you can update the Flask application code to fetch the Windows Authentication user ID. The following code snippet demonstrates how this was done:

 

from flask import Flask, request, render_template

import os

import win32api

import win32security

 

def create_app():

    app = Flask(__name__)

 

    @app.route("/")

    def hello_world():

        s_vars = request.environ

        user = os.environ.get('USERNAME')

        handle_str = request.headers['x-iis-windowsauthtoken']

        handle = int(handle_str,16)

        win32security.ImpersonateLoggedOnUser(handle)

        user1 = win32api.GetUserName()

        win32api.CloseHandle(handle)

        return f"Hello World!: {user1}"

   

    return app

 

This code snippet demonstrates how to use the win32api and win32security modules to impersonate the logged-on user and retrieve their username. The important element here is the x-iis-windowsauthtoken header, which contains the Windows Authentication token passed on by the HttpPlatformHandler.

 

Ensure Dependencies:

Please ensure that the pywin32 package is installed, as it provides the necessary functionality to interact with Windows APIs within the Python environment.

 

 

For further information, refer to the following resources:

 

Published Aug 29, 2024
Version 1.0
No CommentsBe the first to comment