Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check, if browser has cookies enabled in web app?

I decided to re-write the question as I found some info on how to accomplish the above: http://msdn.microsoft.com/en-us/library/aa289495%28v=vs.71%29.aspx

However, my problem is that I'm trying to do all that on the Page_Load event of Login.aspx.cs.

Initially it appears to be working fine until I attempt to actually log in by entering my credentials and clicking the Login button. Then all hell breaks lose and I get an endless loop. It keeps going back and forth between Page_Loads on Login.aspx.cs and TestForCookies.aspx.cs. Each time Redirect URL grows by another "?AcceptCookies=1". Is there a work around to this?

Login.aspx.cs code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Request.QueryString["AcceptsCookies"] == null)
        {
            Response.Cookies["TestCookie"].Value = "ok";
            Response.Cookies["TestCookie"].Expires = DateTime.Now.AddMinutes(1);
            Response.Redirect(BasePage.ResolveUrl("~/Common/TestForCookies.aspx?redirect=" + Server.UrlEncode(Request.Url.ToString())));
        }
        else
        {
            LoginBox.InstructionText = "Accept cookies = " + Request.QueryString["AcceptsCookies"];
        }
    }

}

TestForCookies.aspx.cs code:

protected void Page_Load(object sender, EventArgs e)
{
    string redirect = Request.QueryString["redirect"];

    string acceptsCookies = null;
    // Was the cookie accepted?
    if (Request.Cookies["TestCookie"] == null)
    {
        // No cookie, so it must not have been accepted
        acceptsCookies = "0";
    }
    else
    {
        acceptsCookies = "1";
        // Delete test cookie
        Response.Cookies["TestCookie"].Expires = DateTime.Now.AddDays(-1);
    }

    string url = redirect + "?AcceptsCookies=" + acceptsCookies;


    Response.Redirect(url);
}
like image 759
KoturB Avatar asked Nov 04 '22 04:11

KoturB


1 Answers

This can be hairy. What I've done on my login page is basically these steps:

  1. On the 'login' click post-back to the server, verify the user's credentials. If login was successful...
  2. Set my cookie and send JS to click a hidden 'confirm cookies' button back to the browser. This is an additional round-trip but the cookie should be part of the payload both ways.
  3. Back on the server in the handler for the 'confirm cookies' button I check for the cookie. if it's there, we're good and I redirect. If not, I send content back saying cookies are disabled with a link on how to enable them.

Hope this helps!

like image 167
n8wrl Avatar answered Nov 09 '22 08:11

n8wrl