Question

Im using asp.net 4.0 and Form auth. To check if a user is authenticated or not, i use User.Identity.IsAuthenticated. Most of time it works perfect but i dont know how, sometimes it returns false even if user has auth. My web.config:

<authentication mode="Forms">
    <forms name=".xyz" loginUrl="~/" timeout="120" protection="All" path="/" slidingexpiration=true/>
</authentication>

In global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    FormsIdentity id = new FormsIdentity(authTicket);
    GenericPrincipal principal = new GenericPrincipal(id, roles);

    Context.User = principal;
}

and in login page:

FormsAuthenticationTicket authTick = new FormsAuthenticationTicket(1, email.Text, DateTime.Now, DateTime.Now.AddDays(360), true, password.Text, FormsAuthentication.FormsCookiePath);
string encriptTicket = FormsAuthentication.Encrypt(authTick);

HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encriptTicket);
authCookie.Expires = DateTime.Now.AddDays(360);
Response.Cookies.Add(authCookie);

I also use ajax request in every 5 min. to keep session alive and this also reset auth timeout because slidingexpiration value. I don't know what is wrong with it. sometimes same session and in same minute, it returns false for one page even if it returns true for all the other page. I never got this error but my visitors claim about that problem.

Was it helpful?

Solution

i found the problem. The problem was about difference between www.address.com and address.com. www version pretend like a sub domain and creates new session and auth. If server redirects to www address when user came without www prefix, error happens. I will try url rewriting to solve it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top