且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 09:19:52

好的,所以我对此进行了一些研究,最后回顾了

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

然后找出一种方法后,我想发布此答案,以便1)我以后可以找到它,2)至少是这样,以防其他人想知道.

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.

您需要的只是 pywin32 软件包:

pip install pywin32

使用Python完成的示例:

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