且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net cookie、身份验证和会话超时

更新时间:2023-02-17 11:31:50

尽可能地避免使用 session,如果你能在没有看到的情况下离开,它会使多服务器部署变得更容易一些.可能,姓名和电子邮件是 cookie 的简单候选者.伪造 cookie 很容易,因此根据您的安全需要,用户 ID 可能不是一个好主意.

Avoid using session as much as you can, if you can get away without seesion it makes multi-server deployments qutie a bit easier. Probably, Name and email are easy candidates for cookies. It's easy to fake a cookie, so userID may not be a good idea depending on your security needs.

表单身份验证 cookie 已加密,您可以向这些 cookie 添加额外数据(请参阅下面的详细信息).它可能是可破解的,但不像简单的 cookie 那样容易.

The forms authentication cookies are encrypted and you can add extra data to those cookies (See details below). It's probably hackable but not nearly as easily as a simple cookie.

这是我过去使用的代码,略有修改以删除一些项目特定的细节.在登录控件的 LoggedIn 事件中调用它.

Here is the code I have used in the past slightly modified to remove some project specific details. Call this in the LoggedIn event of the login control.

void AddUserIDToAuthCookie(string userID)  
{  
  //There is no way to directly set the userdata portion of a FormAuthenticationTicket  
  //without re-writing the login portion of the Login control  
  //  
  //I find it easier to pull the cookie that the Login control inserted out  
  //and create a new cookie with the userdata set  

  HttpCookie authCookie = Response.Cookies[AUTH_COOKIE];
  if(authCookie == null)
  {
    return;
  }

  Response.Cookies.Remove(AUTH_COOKIE);

  FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
  var newTicket =
    new FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, oldTicket.IssueDate, oldTicket.Expiration,
                                  oldTicket.IsPersistent, userID, oldTicket.CookiePath);

  authCookie.Value = FormsAuthentication.Encrypt(newTicket);

  Response.Cookies.Add(authCookie);
}

仅供参考,我从一个旧项目中复制了它并在此处对其进行了编辑以删除一些项目特定的位,因此它可能无法编译,但它会非常接近.

FYI, I copied this from an old project and edited it here to remove some project specific bits, so it may not compile, but it'll be very close.

要在您的网页中获取 ID...

To get the ID in your webpage...

FormsAuthenticationTicket ticket = ((FormsIdentity) Page.User.Identity).Ticket;
string id = ticket.UserData;

我使用这种机制来存储一个不属于 aspnetdb 用户数据的 id.如果您的所有身份数据都由 aspnetdb 处理,您可能只需要访问 Page.User.Identity 对象.

I used this mechanism to store an id that was not part of the aspnetdb user data. If all your identity data is handled by the aspnetdb, you may only need to access the Page.User.Identity object.