0

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.

genesistr
  • 147
  • 2
  • 9

1 Answers1

2

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.

genesistr
  • 147
  • 2
  • 9
  • For me it was a Web.config transform that I forgot about. – David d C e Freitas Mar 18 '14 at 23:54
  • @DaviddCeFreitas, can you provide more details about your solution – ebram khalil Nov 27 '14 at 15:55
  • @ebramtharwat, I had one of those production/development web.config.debug kind of transform files that was changing the values after building. Try expand the web.config file in visual studio browser, or check in your project folder if you have other web.config.* files that might be transforming or changing your values on build. – David d C e Freitas Nov 28 '14 at 08:19