获取Windows或IIS用户无需访问页用户、Windows、IIS

2023-09-05 03:08:59 作者:顾辰西

我有一个.NET程序集(可悲的是我们坚持在.NET 3.5中),它可以使用1:

I have a .Net assembly (sadly we're stuck in .Net 3.5) which may be used either:

在.Net应用程序(控制台应用程序,Windows窗体应用程序),在系统上本地运行,或

In a .Net application (console app, Windows Forms app) run locally on the system, or

在使用Windows身份验证的IIS Web应用程序

In an IIS web application using Windows authentication

...并需要获得当前用户。

...and need to get the "current user".

通常为#1我会使用 System.Security.Principal.WindowsIdentity.GetCurrent(),但不会对#2工作,因为这将是用户帐户IIS应用程序在其下运行(应用程序池,例如);和#2我会使用 Page.User.Identity 的处理程序的要求,但在这种情况下,我没有访问该页面。

Normally for #1 I'd use System.Security.Principal.WindowsIdentity.GetCurrent(), but that won't work for #2 because it'll be the user account the IIS app is running under (the app pool, for instance); and for #2 I'd use Page.User.Identity in the handler for the request, but in this case, I don't have access to that page.

我想我可以有一个让IIS应用程序通过的组装方法,而用户属性是不是虚拟的,所以理论上恶意的应用程序无法试喂我错了用户身份,但似乎pretty的狡猾。有没有更好的办法?

I suppose I could have a method that let an IIS application pass the Page to the assembly, and the User property isn't virtual, so in theory a malicious app couldn't try to feed me the wrong user identity, but it seems pretty dodgy. Is there a better way?

我们的目标是通过Windows身份验证来识别用户(通过登录[#1]或IIS使用Windows身份验证[2])。如果我要它完全错误的,我所有的耳朵怎么做正确。 : - )

The goal is to identify the user via Windows authentication (either via login [#1] or IIS using Windows auth [#2]). If I'm going about it completely wrong, I'm all ears for how to do that properly. :-)

推荐答案

HttpContext.Current.User 显然只在IIS的环境中工作。 Thread.CurrentPrincipal中将包含在IIS实际的认证数据,但将保留为空的桌面应用程序。这样做的优点是,它会饶你需要添加的引用的System.Web 组件(桌面应用程序)。 System.Security.Principal.WindowsIdentity.GetCurrent()将工作的桌面应用程序,但在IIS它会返回应用程序池的用户,而不是为经过验证的用户HTTP请求。​​

HttpContext.Current.User would obviously work in IIS environment only. Thread.CurrentPrincipal would contain the actual authentication data in IIS but would remain empty for desktop application. The advantage here is that it will spare you from the need to add a reference to System.Web assembly (in desktop application). System.Security.Principal.WindowsIdentity.GetCurrent() would work for desktop application but in IIS it will return the Application-Pool user, not the authenticated user for the HTTP request.