这就是你需要的。当你使用内置在FormsAuthentication中的更高级别的方法时,ASP.NET会为此负责,但是在低级别上,需要创建一个身份验证 cookie。
if (Membership.ValidateUser(username, password))
{
string userData = string.Join("|",GetCustomUserRoles());
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
我不确定为什么您想要在此处执行自定义操作。如果您想要更改用户数据存储的实现方式以及用户身份验证方法,则最佳做法是创建自定义的MembershipProvider
。自己编写解决方案并踩入身份验证 cookie 可能会导致软件中引入安全漏洞的高概率。
我不理解您的第二部分。如果您想返回用户到登录之前正在访问的页面,则只需要调用FormsAuthentication.GetRedirectUrl
。否则,您可以根据需要执行任何操作,在配置中重定向到 URL。
通常,要读取 FormsAuthentication cookie,您需要在 HttpModule 或 Global.asax 中挂钩 AuthenticateRequest
事件,并设置用户 IPrinciple
上下文。
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if(authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[]{'|'});
IIdentity id = new FormsIdentity( authTicket );
IPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
}
DateTime.Now.AddMinutes(30)
改为DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes)
- LawManDateTime.Now.Add(FormsAuthentication.Timeout)
。但这也不是什么大问题。而且将其转换为分钟再转回去也没有什么损害,只是多了几个CPU使用周期。 - Shawn Kovac