Skip to content Skip to sidebar Skip to footer

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 Win

Solution 1:

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}")
    
    

Post a Comment for "How To Get The Authenticated User Name In Python When Fronting It With IIS HTTP PlatformHandler And Using Windows Auth?"