【问题标题】:C# MVC Application - Change Session ID without losing session dataC# MVC 应用程序 - 更改会话 ID 而不会丢失会话数据
【发布时间】:2013-08-03 02:15:55
【问题描述】:

我正在尝试解决与 MVC 4 应用程序中的会话固定相关的问题 (https://www.owasp.org/index.php/Session_fixation)。

当用户进入登录页面时,清除所有会话和与会话相关的 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 信息,防止之前固定会话。问题是在重新生成 SessionID 时,保存在 Session["UserInfo"] 的所有用户信息都丢失了。

我尝试按照这篇博文 (http://weblogs.asp.net/anasghanem/archive/2008/12/16/programmatically-changing-the-session-id.aspx) 中的建议创建新会话或更改当前会话 ID:

        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,你无能为力,但如果你使用基于Cache的层,例如,Memcached,你可以很容易地改变很多并保留所有值
  • 感谢@balexandre 的快速回复。我正在搜索 Memcached,因为我以前从未听说过它。我得到了这个:link 和这个:link 这是我应该寻找的吗?使用此解决方案是否有任何问题、风险或困难?再次感谢。

标签: c# asp.net-mvc session


【解决方案1】:

答案是您应该在执行此操作之前将所有数据保存到数据库中。您真的不应该将 Session 用于任何无法从数据库重新生成的东西,因为 IIS 可以随时以任何原因(或没有原因)终止您的会话。 Session 只是一种临时存储机制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2015-09-22
    • 2020-07-11
    • 2012-10-18
    • 2015-04-18
    相关资源
    最近更新 更多