你在这里。当您使用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饼干,通常你会在一个HTTP模块或在Global.asax钩AuthenticateRequest
事件,并设置用户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;
}
}
乌尔答案可以帮助我... u能请我需要写什么代码来读取验证Cookie的身份验证后的内容。 FormsAuthentication.SetAuthCookie(userName,createPersistentCookie); SetAuthCookie创建一个身份验证cookie,我需要从服务器端写入该cookie的内容?请你帮忙。日Thnx。 :) – Thomas
我们可以使用jquery从客户端创建表单身份验证Cookie吗? – Thomas
我已更新以显示您还可以如何阅读cookie。不,您不能从客户端进行设置,因为这会带来安全风险,您将无法执行需要服务器端密钥的加密。 auth cookie应该始终是HttpOnly。唯一的办法就是创建一个AJAX请求并让cookie设置为服务器端,在这种情况下,您需要确保您通过SSL传递任何凭据。 – TheCodeKing