1

我正在处理 AspNet Web 应用程序中的自定义身份验证 cookie。

使用asp:Login组件,以下是用户的身份验证方式:

void L_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if (L.UserName == "john" && L.Password == "cookie")
        {
            FormsAuthenticationTicket ticket = 
              new FormsAuthenticationTicket(1, "john", 
                                            DateTime.Now, 
                                            DateTime.Now.AddSeconds(30),
                                            false, "");

            var cookieConnexion = new HttpCookie("myCookie");
            cookieConnexion.Value = FormsAuthentication.Encrypt(ticket);
            cookieConnexion.Expires = ticket.Expiration;
            this.Response.Cookies.Set(cookieConnexion);

            Z.Text = "<a href='/Prive/Home.aspx'>next</a>";
        }
    }

首先,我不设置e.Authenticated = true或者.ASPXAUTHcookie会被创建。我不想要那个。第二,我不会Response.Redirect

现在,在 Global.asax 中,用户设置为 current HttpContext

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
   if (Request.IsAuthenticated)
   {

   }
   else
   {
        var cookie = this.Request.Cookies["myCookie"];
        if (cookie != null)
        {
           var ticket = FormsAuthentication.Decrypt(cookie.Value);

           if (ticket != null)
           {
              HttpContext.Current.User = 
                 new ClientRolePrincipal(new GenericIdentity(ticket.Name));

              ticket = new FormsAuthenticationTicket(1, ticket.Name, 
                                 DateTime.Now, 
                                 DateTime.Now.AddSeconds(30), 
                                 false, ticket.UserData);

              cookie.Value = FormsAuthentication.Encrypt(ticket);
              cookie.Expires = ticket.Expiration;
              this.Response.Cookies.Set(cookie);
            }
         }
     }
 }

对应用程序的第一个请求(使用 chrome 开发工具,我在请求/响应标头中跟踪 cookie):

  • 请求中的 0 个 cookie
  • 0 cookie 响应:ASP.NET_SessionId

用户登录:

  • 请求中的 1 个 cookie:ASP.NET_SessionId
  • 1 个 cookie 响应:myCookie

用户浏览到 Home.aspx:

  • 请求中的 2 个 cookie:ASP.NET_SessionId、myCookie
  • 1 个 cookie 响应:myCookie(已更新)

好的。

现在,如果PreRender我显示 this.Request.Cookies 中包含的元素,我会看到两次myCookie。为什么?

  • ASP.NET_SessionId,域 '',路径 '/',值 = nk1cy255quh32o45hxtg4x55
  • myCookie,域 '',路径 '/',值 = BF6246B7E5A5100AA59A7B7237B446...
  • myCookie,域 '',路径 '/',值 = BF6246B7E5A5100AA59A7B7237B446...
4

0 回答 0