Skip to content

Instantly share code, notes, and snippets.

@asok-mirror
Last active November 6, 2022 18:05
Show Gist options
  • Save asok-mirror/a4d2e394eda75ec05c543fc24418ccdb to your computer and use it in GitHub Desktop.
Save asok-mirror/a4d2e394eda75ec05c543fc24418ccdb to your computer and use it in GitHub Desktop.
protected void Application_BeginRequest(object sender, EventArgs e)
{
//perform the validation for the already created session. For a new session this check will be ignored.
if (Request.Cookies["ASP.NET_SessionId"]?.Value != null && _isNotARedirect)
{
var hash = GenerateSessionHash().AsSpan();
//verifies the request is from originator or not
if ((!MemoryExtensions.Equals(hash, Request.Cookies["ASP.NET_SessionId"].Value.AsSpan(Request.Cookies["ASP.NET_SessionId"].Value.Length - hash.Length), StringComparison.Ordinal)
|| !MemoryExtensions.Equals(hash, Request.Cookies["SomeAuth2"].Value.AsSpan(Request.Cookies["SomeAuth2"].Value.Length - hash.Length), StringComparison.Ordinal)))
{
_log.Debug("cookies are tampered, rejected the request");
EndResponse();
}
//if the request is valid, then re-assign the framework generated sessionid back.
Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.AsSpan(0, Request.Cookies["ASP.NET_SessionId"].Value.Length - hash.Length).ToString();
Request.Cookies["SomeAuth2"].Value = Request.Cookies["SomeAuth2"].Value.AsSpan(0, Request.Cookies["SomeAuth2"].Value.Length - hash.Length).ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment