繁体   English   中英

从Thread.CurrentPrincipal设置HttpContext.Current.User

[英]Set HttpContext.Current.User from Thread.CurrentPrincipal

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

经过身份验证的过程后,当我尝试将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
    }

在此先感谢您的帮助。

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

表单身份验证在每个请求上使用它自己的主体分配。 这就是为什么您看到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的值,但是我建议您仔细检查如何设置主体。 我建议您在此代码上放置断点,然后在调试器中运行它。 逐行查看发生了什么。

很抱歉VB(糟糕的语言),但是应该可以回答您的问题...

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

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

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

那应该给您您需要的。 非常适合我:)

当您使用基于表单的身份验证(FBA)时,您将在ASP.NET中获得一个GenericPrincipal。 这是正常现象,您没有做错任何事情。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM