sliding expiration .net session - c#

I'm trying to allow my users to stay within the website indefinitely, so that if there session hasn't expired yet i will slide the expiration to another few minutes, but it doesn't seem to work.
my code:
private void Application_EndRequest(object sender,EventArgs e)
{
if(Response.Cookies["siteCookie"] != null)
{
Response.Cookies["siteCookie"].Expires = DateTime.UtcNow.AddHours(1);
}
}
but only in the initial request when the end user doesn't have my cookie yet the server returns Set-Cookie header, but not on the requests that follows

Response.Cookies contains a list of cookies that are being set as part of the current request/response. It does not contain cookies that were set earlier, although those will typically appear in Request.Cookies. So you could use something like this:
private void Application_EndRequest(object sender,EventArgs e)
{
var oldCookie = Request.Cookies["SiteCookie"];
if (oldCookie != null)
{
var newCookie = new HttpCookie("SiteCookie", oldCookie.Value);
newCookie.Expires = System.DateTime.Now.AddHours(1);
Response.AppendCookie(newCookie);
}
}

Related

How to prevent client to view WebResource.axd until user login?

My Web application has WebResource.axd handler. but it is visible either user has session or not.
Is it possible to prevent client to browse WebResource.axd before logging in?
I solved the problem by adding this code in Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpRequest request = this.Request;
HttpResponse response = this.Response;
if (request.RawUrl.IndexOf(".axd") > -1)
{
if (!IsLogined())
{
response.Redirect("/notauth.js");
}
}
}

Prevent change "ASP.NET_SessionId" by user c#

I tried to prevent user for changing the "ASP.NET_SessionId"
I tried this code:
Response.Cookies["ASP.NET_SessionId"].Value = GenerateHashKey();
But my session (Session["userId"]) was removed when I tried to set the cookie
Here is some code that I tried without success:
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();
}
}
How to prevent the user for set session
Looks like you are trying to secure your session value from tampering? If you set the value yourself, you override the session identifier and destroy the purpose of the asp session cookie.
ASP.Net_SessionId is a cookie which is used to identify the users session on the server. The session being an area on the server which can be used to store data in between http requests.
If you are trying to solve the session fixation problem, which is the only vulnerability of asp session cookie, then you need to introduce a new cookie like this: https://medium.com/#grep_security/session-fixation-broken-authentication-and-session-management-c37ce0111bf5

Why is my cookie showing as null in C# ASP.NET Empty Web Project?

Working on a Black Jack game and I am trying to save the Player's balance as a cookie. I cannot get it to work properly. When exiting the browser and reloading the webpage, the cookie is always null.
I declared the cookie as a static variable so I can access in a later method to send it to the client.
public partial class BlackJack : System.Web.UI.Page
{
public static HttpCookie cookie;
protected void Page_Load(object sender, EventArgs e)
{
cookie = Request.Cookies["Balance"];
if (!IsPostBack)
{
if (cookie != null)
{
PlayerBalance = Convert.ToInt32(cookie.Values["balance"]);
if (PlayerBalance == 0)
{
PlayerBalance = 250;
}
}
else
{
PlayerBalance = 250;
HttpCookie cookie = new HttpCookie("Balance");
cookie.Values.Add("balance", PlayerBalance.ToString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
PlayerBet = 0;
}
Then in a later method that runs after each hand, I save the cookie with Response.Cookies.Add().
public void Other Method()
{
cookie = Request.Cookies["Balance"];
cookie.Values["balance"] = PlayerBalance.ToString();
Response.Cookies.Add(cookie);
}
But if I close out of a browser and return to the site, the cookie is always null.
Cookies are non-persistent by default. That means as longas you don't specify an expiration date for the cookie the browser clears it, when you close the browser.
So in this case you'll need a persistent cookie, which can be created by setting the Expires-property:
var cookie = new HttpCookie("Balance");
cookie.Expires = DateTime.Now.AddDays(1);
For more details have a look at this comprehensive article: https://msdn.microsoft.com/en-us/library/ms178194.aspx
But note what #CodeCaster already said: A cookie is only a small piece of text which can be easily modified by the client. So you should consider storing sensitive information elsewhere. Or at least you should consider encrypting your cookies.
Remove the line
public static HttpCookie cookie;
It will create a non-thread safe type of cookie .In mutitreaded environment it will have mess up value.
This works fine..Your static causes the problem.Create cookie every every method and Dump it on browser Response.Cookies.Add(cookie) with same name
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("Balance");
cookie.Values.Add("balance", "akash".ToString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
protected void Button1_Click(object sender, EventArgs e)
{
var cookie = Request.Cookies["Balance"];
cookie.Values["balance"] = "ggg".ToString();
Response.Cookies.Add(cookie);
}

Make ASP.NET_SessionId cookie not httpOnly

The cookie used for session in ASP.NET MVC is httpOnly (property set to true).
Is there a way to make it not httpOnly?
I want to be able to access this cookie from javascript.
Even if it is less secure than the "What if all the universe stands against me?!" default setting.
If you REALLY need it you could try to add this to your Global.asax:
void Application_EndRequest(Object sender, EventArgs e)
{
if (Response.Cookies.Count > 0)
{
foreach (string s in Response.Cookies.AllKeys)
{
if (s == "ASP.NET_SessionId")
{
Response.Cookies["ASP.NET_SessionId"].HttpOnly = false;
}
}
}
}
Solution was taken from here.
I built a system that uses cookies to store search params across the site.
On the home page there are links and I wanted to use jQuery to save a cookie with the item id in it.
But on click the user is then sent to an advanced search page where they can use .net controls to modify the search. The cookies are saved again but they needed to be writable by the js on the home page when the user browsed back.
So I set HttpOnly like this:
var cookie = new HttpCookie(name)
{
Value = val,
HttpOnly = false // #DEV search cookies can be modified by JS
};
HttpContext.Current.Response.Cookies.Add(cookie);

HTTP Module and Cookies in Sharepoint 2007

I have some proof concept code for a HTTP module. The code checks to see if a cookie exists, if so it retrieves a value, if the cookie does not exist it creates it and sets the value.
Once this is done I write to the screen to see what action has been taken (all nice and simple). So on the first request the cookie is created; subsequent requests retrieve the value from the cookie.
When I test this in a normal asp.net web site everything works correctly – yay! However as soon as I transfer it to SharePoint something weird happens, the cookie is never saved - that is the code always branches into creating the cookie and never takes the branch to retrieve the value - regardless of page refreshes or secondary requests.
Heres the code...
public class SwithcMasterPage : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
// register handler
context.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
void PreRequestHandlerExecute(object sender, EventArgs e)
{
string outputText = string.Empty;
HttpCookie cookie = null;
string cookieName = "MPSetting";
cookie = HttpContext.Current.Request.Cookies[cookieName];
if (cookie == null)
{
// cookie doesn't exist, create
HttpCookie ck = new HttpCookie(cookieName);
ck.Value = GetCorrectMasterPage();
ck.Expires = DateTime.Now.AddMinutes(5);
HttpContext.Current.Response.Cookies.Add(ck);
outputText = "storing master page setting in cookie.";
}
else
{
// get the master page from cookie
outputText = "retrieving master page setting from cookie.";
}
HttpContext.Current.Response.Write(outputText + "<br/>");
}
private string GetCorrectMasterPage()
{
// logic goes here to get the correct master page
return "/_catalogs/masterpage/BlackBand.master";
}
This turned out to be the authentication of the web app. To work correctly you must use a FQDM that has been configured for Forms Authentication.
You can use Fiddler or FireBug (on FireFox) to inspect response to see if your cookie is being sent. If not then perhaps you can try your logic in PostRequestHandlerExecute. This is assuming that Sharepoint or some other piece of code is tinkering with response cookies. This way, you can be the last one adding the cookie.

Categories

Resources