pythoniiswindows-authenticationpywin32httpplatformhandler

How to get the authenticated user name in Python when fronting it with IIS HTTP PlatformHandler and using Windows auth?


HttpPlatformHandler supports forwarding the auth token by enabling the forwardWindowsAuthToken setting in the web.config. This sounds like a useful feature when needing to use Windows Integrated Authentication. The document on this is very vague and does not go into explaining how one could use this token to get the authenticated user name.

If this setting is set to true, the token will be forwarded to the child process listening on %HTTP_PLATFORM_PORT% as a header 'X-IIS-WindowsAuthToken' per request. It is the responsibility of that process to call CloseHandle on this token per request. The default value is false.

In my use-case, I needed to use Windows Integrated Authentication with Python, so did a setup with IIS fronting and using HTTP Platform Handler forward requests to Python.

The question is, how do I get the user name from the provided token in Python ? The token in the 'X-IIS-WindowsAuthToken' header seems like a 3 char hex like 22b.


Solution

  • Okay, so I've researched this a bit and ended up reviewing how Microsoft.AspNetCore.Server.IISIntegrateion.AuthenticationHandler did it.

    Then after figuring out one way, I wanted to post this answer so 1) I can find it later, 2) at least it's up on SO in case anyone else is wondering.

    Okay, so the hex value is the handle and with the handle we can call impersonate user then get username, done.

    All you need is the pywin32 package:

    pip install pywin32

    Complete example in Python:

    import win32api
    import win32security
    if 'x-iis-windowsauthtoken' in request.headers.keys():
        handle_str = request.headers['x-iis-windowsauthtoken']
        handle = int(handle_str, 16) # need to convert from Hex / base 16
        win32security.ImpersonateLoggedOnUser(handle)
        user = win32api.GetUserName()
        win32security.RevertToSelf() # undo impersonation
        win32api.CloseHandle(handle) # don't leak resources, need to close the handle!
        print(f"user name: {user}")