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

久未见 提交于 2021-02-08 07:40:48

问题


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.


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


来源:https://stackoverflow.com/questions/62806295/how-to-get-the-authenticated-user-name-in-python-when-fronting-it-with-iis-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!