使用FormsAuthentication
我们编写如下代码:
if (IsValidUser())
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie);
}
如何手动创建身份验证Cookie而不是撰写FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)
?
如何将登录页面中的重定向网址存储在字符串变量中,而不是写入FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie)
?
答案 0 :(得分:83)
你走了。当您使用FormsAuthentication中内置的更高级别方法时,ASP.NET会为您解决此问题,但在较低级别,这是创建身份验证cookie所必需的。
if (Membership.ValidateUser(username, password))
{
// sometimes used to persist user roles
string userData = string.Join("|",GetCustomUserRoles());
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
isPersistent, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
// Your redirect logic
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
我不确定你为什么要在这里做一些自定义的事情。如果要更改存储用户数据的位置以及用户进行身份验证的方式,则最佳做法是创建自定义MembershipProvider
。滚动您自己的解决方案并弄乱身份验证cookie意味着很有可能在您的软件中引入安全漏洞。
我不明白您的第2部分。如果您想要将用户返回到他们退回登录时尝试访问的页面,则只需要调用FormsAuthentication.GetRedirectUrl。如果不在此处执行任何操作,请根据需要重定向到存储在配置中的URL。
要读取FormsAuthentication cookie,通常可以将AuthenticateRequest
事件挂钩到HttpModule或Global.asax中,并设置用户IPrinciple
上下文。
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if(authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching roles in userData field then extract
string[] roles = authTicket.UserData.Split(new char[]{'|'});
// Create the IIdentity instance
IIdentity id = new FormsIdentity( authTicket );
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, roles);
// Set the context user
Context.User = principal;
}
}
答案 1 :(得分:-9)
回答有关此帖子的投票数量的更新 使用以下用户信息创建cookie的正确方法,
登录页面加载时的Cookie验证
if (HttpContext.Current.User.Identity.IsAuthenticated)
在经过身份验证的用户登录期间创建Cookie,
FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), true);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
txtUserName.Text.Trim(),
DateTime.Now,
(chkRemember.Checked) ? DateTime.Now.AddHours(6) : DateTime.Now.AddHours(2),// Specify timelimit as required
true,
string.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = (chkRemember.Checked) ? DateTime.Now.AddHours(6) : DateTime.Now.AddHours(2);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
以下是已投票的答案 - 在Cookie中添加加密密码的原因。
创建cookie的另一种方式,
HttpCookie toolCookie = new HttpCookie("xyz");
toolCookie["UserName"] = userName;
toolCookie["Password"] = StringCipher.Encrypt(password, "#!");
toolCookie.Expires = DateTime.Now.AddMinutes(chkRemember.Checked ? 30 : -30);
Request.Cookies.Add(toolCookie);
获取现有Cookie详细信息
HttpCookie user = Request.Cookies["xyz"];
if(user != null)
{
string username = user["UserName"];
string password = user["Password"] != null ? StringCipher.Decrypt(user["Password"], "#!")
}
此处数据安全是一个静态类。
加密和解密功能Encrypt & Decrypt