【问题标题】:Where to create custom IPrincipal object?在哪里创建自定义 IPrincipal 对象?
【发布时间】:2011-08-14 18:07:20
【问题描述】:

我在 global.asax 中使用 Application_PostAuthenticateRequest 事件来创建自定义 IPrincipal 对象

void Application_PostAuthenticateRequest(object sender, EventArgs args)
{
    if (Context.User.Identity.IsAuthenticated == true)
        if (Context.User.Identity.AuthenticationType == "Forms")
        {                 
              Context.User = new CustomPrincipal(Context.User);
              Thread.CurrentPrincipal = Context.User;
        }                
}

在我想要获取有关登录用户的更多信息的应用程序中使用。我认为它会在用户进行身份验证时被调用一次,但我注意到它会在每个页面请求中为同一个登录用户调用几次。我发现即使从 AppThemes 请求图像也会调用这个方法!

我应该在哪里创建该对象以避免为每个用户多次调用此方法?

【问题讨论】:

    标签: asp.net forms-authentication


    【解决方案1】:

    我找到了我的问题的答案。

    在 loggin_in 事件中,我应该保存身份验证 cookie(我可以将以后需要的所有信息存储在 UserData 属性中的 customPrincipal 中),在 Application_PostAuthenticateRequest 中,我应该从该 cookie 创建 CustomPrincipal。 这样,这个事件会触发每个请求,但我没有点击数据库 - 我从 cookie 中读取数据。

    我关注了http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html

    在我的例子中,代码是:

    void Application_PostAuthenticateRequest(object sender, EventArgs args)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie == null)
                return;
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            string[] customData = authTicket.UserData.Split(new Char[] { '|' });
    
            if (Context.User.Identity.IsAuthenticated == true)
            {
                if (Context.User.Identity.AuthenticationType == "Forms")
                {
                    Context.User = new CustomPrincipal(customData, Context.User);
                    Thread.CurrentPrincipal = Context.User;
                }
            }
    }
    

    【讨论】:

      【解决方案2】:

      Context.User 不会跨请求保存新主体;您必须在每个请求上创建自定义主体。所以最好把这段代码留在这里。否则,它将恢复为 FormsPrincipal 或 WindowsPrincipal,具体取决于应用程序身份验证模式。

      HTH,

      布赖恩

      【讨论】:

        猜你喜欢
        • 2017-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-19
        • 2018-02-27
        • 1970-01-01
        相关资源
        最近更新 更多