我正在尝试解决与 MVC 4 应用程序中的 session 固定相关的问题 (https://www.owasp.org/index.php/Session_fixation)。
当用户进入登录页面时清除所有 session 和 session 相关的 cookie。代码:
Session.Clear();
Session.Abandon();
Session.RemoveAll();
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
}
应用程序的登录页面要求用户提供凭据和验证码。当用户点击登录按钮时,我们发送一个 ajax 请求。代码:
@using (Ajax.BeginForm("Autenticar", "Login", null, new AjaxOptions { OnComplete = "OnComplete", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { @class = "Exception" }))
{
<fieldset>
<legend>Login Form</legend>
all form inputs
</fieldset>
}
此时我们需要修改Session.SessionID信息,防止之前固定一个session。问题是在重新生成 SessionID 时,保存在 Session["UserInfo"] 中的所有用户信息都丢失了。
我尝试创建一个新 session 或更改当前 session ID,就像这篇博文 (http://weblogs.asp.net/anasghanem/archive/2008/12/16/programmatically-changing-the-session-id.aspx) 中建议的那样:
SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
string OldID = Context.Session.SessionID;
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID,out redirected, out IsAdded);
谁能帮我处理一些有用的信息以将数据保存在新的 SessionID 中?
谢谢。
最佳答案
答案是您应该在执行此操作之前将所有数据保存到数据库中。您真的不应该将 Session 用于无论如何都无法从数据库中重新生成的任何内容,因为 IIS 可以出于任何原因(或没有原因)随时终止您的 session 。 Session只是一种临时存储机制。
关于C# MVC 应用程序 - 在不丢失 session 数据的情况下更改 session ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18006225/