0

i have simple authentication type i chek in DB if userName and password exist i creat FormsAuthenticationTicket and add it HttpContext.Current.Response.Cookies.Add(cookie); when i check HttpContext.Current.User.Identity.IsAuthenticated before request it return false but if i check in global.asax Application_AuthenticateRequest(object sender, EventArgs e) for following request HttpContext.Current.User.Identity.IsAuthenticated return true

public static bool Login(string userName, string pass)
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();
                string comand = string.Format("Select * From ChatUser Where " +
                "userName = '{0}' and pass ='{1}'", userName, pass);
                SqlCommand cmd = new SqlCommand(comand, conn);
                var reader = cmd.ExecuteReader();
                if (!reader.HasRows)
                {
                    conn.Close();
                    return false;
                }
                while (reader.Read())
                {
                    string id = reader["id"].ToString();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1, id, DateTime.Now, DateTime.Now.AddMinutes(30),
                    false, null, FormsAuthentication.FormsCookiePath);
                    string hashCookies = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
                    HttpContext.Current.Response.Cookies.Add(cookie);

                }
                conn.Close();
                JoinMesage();
                return true;
            }


            catch (Exception ex)
            {
                //write in log file
                return false;
            }
        }
    }

    public static void JoinMesage()
    {
        string userId;
        if (HttpContext.Current.User != null)
        {
            userId = HttpContext.Current.User.Identity.Name;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string comand = string.Format("Insert into Messages (userID,mesageDate,userStatus)"
                    + " Value('{0}','{1}','{2}')", userId, DateTime.Now, true);
            }
        }


    }
HaikMnatsakanyan
  • 303
  • 2
  • 5
  • 13

1 Answers1

2

Please modify your ticket. it should be

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1, 
    id, 
    DateTime.Now, 
    DateTime.Now.AddMinutes(30),
    true, 
    null, 
    FormsAuthentication.FormsCookiePath);

and set authentication type in custom identity class please follow the link:

http://www.asp.net/web-forms/tutorials/security/introduction/forms-authentication-configuration-and-advanced-topics-cs

It will solve it.

Prasad Jadhav
  • 5,090
  • 16
  • 62
  • 80
Umesh Garg
  • 21
  • 2