从Thread.CurrentPrincipal设置HttpContext.Current.User

我的应用程序中有一个安全管理器,适用于Windows和Web,过程很简单,只需要用户和pwd并对数据库进行身份validation,然后使用自定义主体设置Thread.CurrentPrincipal。 对于Windows应用程序,这工作正常,但我有Web应用程序的问题。

在身份validation过程之后,当我尝试将Current.User设置为Thread.CurrentPrincipal中的自定义主体时,最后一个包含GenericPrincipal。 难道我做错了什么? 这是我的代码:

为Login.aspx

protected void btnAuthenticate_Click(object sender, EventArgs e) { SecurityManager.Authenticate("user","pwd"); // This is where I set the custom principal in Thread.CurrentPrincipal FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1, "user", DateTime.Now, DateTime.Now.AddMinutes(30), false, ""); string ticket = FormsAuthentication.Encrypt(authenticationTicket); HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket); Response.Cookies.Add(authenticationCookie); Response.Redirect(FormsAuthentication.GetRedirectUrl("user", false)); } 

Global.asax(这是出现问题的地方)

 protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) return; if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; //Here the value is GenericPrincipal } 

在此先感谢您的帮助。

首先:您需要在每个请求上设置主体。

表单身份validation在每个请求上使用它自己的主体分配。 这就是你看到GenericPrincipal的原因

当标准认证机制完成时,我通常会在OnPostAuthenticate中重新分配我的自定义原语。

JFYI,你可以替换

 if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { } 

 FormsIdentity formsIdentity = HttpContext.Current.User as FormsIdentity; if (formsIdentity != null & formsIdentity.IsAuthenticated) { } 

减少if子句的长度

Intellisense告诉我, HttpContext.Current.userSystem.Threading.Thread.CurrentPrincipal都是System.Security.Principal.IPrincipal类型。

如果我理解正确,这意味着语句HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; 将线程主体的值分配给httpcontext用户,而不进行任何转换或转换。

我没有看到你的代码中System.Threading.Thread.CurrentPrincipal设置System.Threading.Thread.CurrentPrincipal的值,但我建议你仔细检查你如何设置主体。 我建议您在此代码上放置断点并在调试器中运行它。 逐行了解发生了什么。

抱歉VB(可怕的语言),但这应该回答你的问题……

http://www.asp.net/security/videos/use-custom-principal-objects

然后将该行代码更改为……

 HttpContext.Current.User = (CustomPrinciple)System.Threading.Thread.CurrentPrincipal; 

这应该会给你你需要的东西。 对我来说很完美:)

使用基于窗体的身份validation(FBA)时,您将在ASP.NET中获得GenericPrincipal。 这是正常的,你没有做错任何事。

你期待什么? 如果您期望使用WindowsPrincipal,则可以在ASP.NET应用程序中使用Windows集成身份validation。