我正在使用AspNet网络应用中的自定义身份验证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
或.ASPXAUTH
cookie。我不希望这样。其次,我不做Response.Redirect
。
现在,在Global.asax中,用户设置为当前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 dev工具,我在请求/响应标头中跟踪Cookie):
用户登录:
用户浏览Home.aspx:
行。
现在,如果在PreRender
上我显示this.Request.Cookies中包含的元素,我会看到两次myCookie
。为什么呢?