防止用户c#更改“ ASP.NET_SessionId”

时间:2020-01-08 06:41:13

标签: c# asp.net-mvc session session-cookies

我试图阻止用户更改"ASP.NET_SessionId"

我尝试了以下代码:

Response.Cookies["ASP.NET_SessionId"].Value = GenerateHashKey();

但是,当我尝试设置Cookie时,我的sessionSession["userId"])已删除

以下是我尝试未成功成功的一些代码:

protected void Application_BeginRequest(object sender, EventArgs e)
{

    //Check If it is a new session or not , if not then do the further checks
    if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)
    {
        string newSessionID = Request.Cookies["ASP.NET_SessionID"].Value;
        //Check the valid length of your Generated Session ID
        if (newSessionID.Length <= 24)
        {
            //Log the attack details here
            Response.StatusCode = 401;
        }

        //Genrate Hash key for this User,Browser and machine and match with the Entered NewSessionID
        if (GenerateHashKey() != newSessionID.Substring(24))
        {
            //Log the attack details here
            Response.StatusCode = 401;
            //throw new HttpException("401");
        }
        //Use the default one so application will work as usual//ASP.NET_SessionId
        Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Substring(0, 24);
    }
}

private string GenerateHashKey()
{
    StringBuilder myStr = new StringBuilder();
    myStr.Append(Request.Browser.Browser);
    myStr.Append(Request.Browser.Platform);
    myStr.Append(Request.Browser.MajorVersion);
    myStr.Append(Request.Browser.MinorVersion);
    SHA1 sha = new SHA1CryptoServiceProvider();
    byte[] hashdata = sha.ComputeHash(Encoding.UTF8.GetBytes(myStr.ToString()));
    return Convert.ToBase64String(hashdata);
}


protected void Application_EndRequest(object sender, EventArgs e)
{
    //Pass the custom Session ID to the browser.
    if (Response.Cookies["ASP.NET_SessionId"] != null)
    {
        Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + GenerateHashKey();
    }

}

如何防止用户设置会话 enter image description here

1 个答案:

答案 0 :(得分:1)

您是否想保护自己的会话价值免遭篡改?如果您自己设置值,则将覆盖会话标识符并破坏asp会话cookie的用途。

ASP.Net_SessionId是一个cookie,用于标识服务器上的用户会话。会话是服务器上的一个区域,可用于在http请求之间存储数据。

如果您要解决会话固定问题(这是asp会话cookie的唯一漏洞),则需要引入一个新的cookie,例如:https://medium.com/@grep_security/session-fixation-broken-authentication-and-session-management-c37ce0111bf5

相关问题