【发布时间】:2020-04-25 16:20:41
【问题描述】:
我试图阻止用户更改"ASP.NET_SessionId"
我试过这段代码:
Response.Cookies["ASP.NET_SessionId"].Value = GenerateHashKey();
但我的session (Session["userId"]) 在我尝试设置 cookie 时被删除了
这是我尝试没有成功的一些代码:
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();
}
}
【问题讨论】:
-
非常不清楚你想要达到什么目的......显然你不能阻止用户发送任何任意数据......但你仍然想保护一些东西......你的威胁是什么试图减轻? (旁注:你很有可能想阅读docs.microsoft.com/en-us/dotnet/api/…)
-
我知道用户可以根据需要设置 cookie,我想阻止它(安全问题)。我尝试创建自己的 cookie 的原因,但是当我尝试它时,控制器中的会话变为 null
标签: c# asp.net-mvc session session-cookies