如何手动创建身份验证cookie而不是默认方法?

Tho*_*mas 50 asp.net

使用FormsAuthentication我们编写这样的代码:

 if (IsValidUser())
 {
      FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
      FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie); 
 }
Run Code Online (Sandbox Code Playgroud)
  1. 如何手动创建身份验证cookie而不是写入FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)

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

The*_*ing 85

干得好.当您使用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));
}
Run Code Online (Sandbox Code Playgroud)

我不确定你为什么要在这里做一些自定义的事情.如果要更改存储用户数据的位置以及用户进行身份验证的方式,则最佳做法是创建自定义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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我已经更新,以显示你如何也可以阅读cookie.不,你不能从客户端设置它,因为这将是一个安全风险,你将无法执行需要服务器端密钥的加密.auth cookie应始终是HttpOnly.唯一的方法是发出一个AJAX请求并让cookie设置为服务器端,在这种情况下,您需要确保通过SSL传递任何凭据. (3认同)
  • 您可以在保存 cookie 实例之前设置 HttpOnly。更新以反映最佳实践:) (2认同)