在IIS HTTP PlatformHandler前面使用Windows身份验证时,如何在Python中获取经过身份验证的用户名? [英] How to get the authenticated user name in Python when fronting it with IIS HTTP PlatformHandler and using Windows auth?

查看:71
本文介绍了在IIS HTTP PlatformHandler前面使用Windows身份验证时,如何在Python中获取经过身份验证的用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpPlatformHandler 支持通过启用web.config中的 forwardWindowsAuthToken 设置来转发身份验证令牌.当需要使用Windows集成身份验证时,这听起来像是一项有用的功能. 文档 对此非常含糊,不解释如何使用此令牌获取经过身份验证的用户名.

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.

如果此设置设置为true,则令牌将转发到子进程以%HTTP_PLATFORM_PORT%作为标题侦听每个请求"X-IIS-WindowsAuthToken".这是它的责任每个请求对此令牌调用CloseHandle的过程.默认值值是假的.

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.

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.

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

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.

推荐答案

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

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

这篇关于在IIS HTTP PlatformHandler前面使用Windows身份验证时,如何在Python中获取经过身份验证的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆