0

I am doing forms authentication as follows:

                if (strRole != null)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                   1,                            // version
                   username,                      // user name
                   DateTime.Now,                 // create time
                   DateTime.Now.AddSeconds(500),  // expire time
                   false,                        // persistent
                   strRole);                     // user data

                string strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
                Context.Response.Cookies.Add(cookie);
                return true;
            }

then on another page i have jQuery as follows

$.ajax({
    type: "POST",
    crossOrigin: true,
    url: "./WebService.asmx/Login",
    data: JSON.stringify({'username':username,'password':password}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (response.d === true) {
            $(location).attr('href', '/dash/dashboard.aspx')
        }
        else {
            ShowErrorModal("Invalid login or password.","login");
        }
    }
});

the issue is in the on_load event of dashboard.aspx page, the following is always false

HttpContext.Current.User.Identity.IsAuthenticated

the question is what does it consider user is not authenticated.

any help will be much appreciated.

user1144596
  • 2,068
  • 8
  • 36
  • 56

1 Answers1

1

Adding the following solved in global.asax.cs the problem

    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;
    }

Taken from https://stackoverflow.com/a/8490241/1144596

Community
  • 1
  • 1
user1144596
  • 2,068
  • 8
  • 36
  • 56