在使用IIS HTTP PlatformHandler和Windows auth前置时,如何在Python中获取经过身份验证的用户名?

2024-06-02 13:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

HttpPlatformHandler通过启用web.config中的forwardWindowsAuthToken设置,支持转发身份验证令牌。 当需要使用Windows集成身份验证时,这听起来像是一个有用的功能。 上面的document非常模糊,没有解释如何使用这个令牌来获取经过身份验证的用户名

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.

在我的用例中,我需要将Windows集成身份验证与Python一起使用,IIS前置和使用HTTP平台处理程序将请求转发到Python的设置也是如此

问题是,如何从Python中提供的令牌中获取用户名? “X-IIS-WindowsAuthToken”头中的令牌看起来像一个3字符的十六进制22b


Tags: thetotoken身份验证httpisonrequest
1条回答
网友
1楼 · 发布于 2024-06-02 13:20:13

好的,我对此进行了一些研究,最后回顾了Microsoft.AspNetCore.Server.IISIntegrateion.AuthenticationHandler是如何做到的

然后,在找到一种方法后,我想发布这个答案,以便1)我可以在以后找到它,2)至少它是打开的,以防其他人想知道

好的,十六进制值就是句柄,通过这个句柄我们可以调用模拟用户,然后得到用户名,完成

您只需要pywin32包:

pip install pywin32

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

相关问题 更多 >