2011-08-27 55 views
46

使用FormsAuthentication我们这样写代码:如何手动创建身份验证Cookie而不是默认方法?

if (IsValidUser()) 
{ 
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
     FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie); 
} 
  1. 我如何手动创建一个身份验证cookie,而不是写的?

  2. 如何将登录页面中的重定向URL存储在字符串变量中,而不是写入FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie)

回答

81

你在这里。当您使用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; 
    } 
} 
+0

乌尔答案可以帮助我... u能请我需要写什么代码来读取验证Cookie的身份验证后的内容。 FormsAuthentication.SetAuthCookie(userName,createPersistentCookie); SetAuthCookie创建一个身份验证cookie,我需要从服务器端写入该cookie的内容?请你帮忙。日Thnx。 :) – Thomas

+0

我们可以使用jquery从客户端创建表单身份验证Cookie吗? – Thomas

+3

我已更新以显示您还可以如何阅读cookie。不,您不能从客户端进行设置,因为这会带来安全风险,您将无法执行需要服务器端密钥的加密。 auth cookie应该始终是HttpOnly。唯一的办法就是创建一个AJAX请求并让cookie设置为服务器端,在这种情况下,您需要确保您通过SSL传递任何凭据。 – TheCodeKing

-7

创建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); 

Reference

获取现有的Cookie信息

HttpCookie user = Request.Cookies["xyz"]; 
if(user != null) 
{ 
    string username = user["UserName"]; 
    string password = user["Password"] != null ? StringCipher.Decrypt(user["Password"], "#!") 
} 

这里Datasecurity是一个静态类。

加密和解密功能Encrypt & Decrypt

+10

切勿将密码放入cookie中。这失败了整个安全cookies的点 –

+0

你能否建议我最好的解决方案相同 – Vijayaraghavan

+0

你可以检查这个例子.. http://www.aspsnippets.com/Articles/Implement-Remember-Me-functionality-using-CheckBox- ASPNet.aspx – Vijayaraghavan