locked
How do i use cookies to store user username and password on signup and then when user login? RRS feed

  • Question

  • User-625131191 posted

    I have a signup form that i used session but each time a user closes browser on next visit the site will be requesting user to login, and because of that i wanted to use a persist cookie to store user username and password. below is my sign up form code, please any help?

      string constr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
                                    using (SqlConnection con = new SqlConnection(constr))
                                    {
                                        using (SqlCommand cmd = new SqlCommand("Insert_Users"))
                                        {
                                            using (SqlDataAdapter sda = new SqlDataAdapter())
                                            {
                                                //Get Filename from fileupload control
                                                // string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                                                //Save images into Images folder
                                                //   FileUpload1.SaveAs(Server.MapPath("UserImages/" + filename));
                                                cmd.CommandType = CommandType.StoredProcedure;
                                                //  cmd1.Parameters.AddWithValue("@UserImageName", filename);
                                                // cmd1.Parameters.AddWithValue("@UserImagePath", "UserImages/" + filename);
                                                cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                                                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                                                cmd.Parameters.AddWithValue("@UserName", UsrNm);
    
                                                cmd.Parameters.AddWithValue("@Password", Encrypt(txtPassword.Text.Trim()));
    
                                                cmd.Parameters.AddWithValue("@BirthDay", txtBirthDay.Text.Trim());
    
                                                cmd.Parameters.AddWithValue("@Country", ddlCountry.Text.Trim());
                                                cmd.Parameters.AddWithValue("@ImageName", imgname);
                                                cmd.Connection = con;
                                                con.Open();
                                                UserID = Convert.ToInt32(cmd.ExecuteScalar());
                                                con.Close();
    
    
                                            }
                                        }
                                        string message = string.Empty;
                                        switch (UserID)
                                        {
                                            case -1:
                                                message = "Username already exists.\\Please choose a different username.";
                                                break;
                                            case -2:
                                                message = "Supplied email address has already been used.";
                                                break;
    
                                           
                                            default:
                                                message = "Registration successful, you may now login.";
                                               // SendActivationEmail(UserID);
                                                break;
                                        }
                                        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
                                    }
                                }
                            }

    Monday, May 7, 2018 3:28 PM

All replies

  • User283571144 posted

    Hi Skyformat48,

    As far as I know,  it isNOT secure to store passwords in cookies because they are available as plain text.

    Normally, we will store the username and a hash of the password and a salt in the cookie, then when you authenticate the cookie, retrieve the password for the given username, re-create the hash with the password and the same salt and compare them.

    More details, you could refer to below codes:

    // Create a hash of the given password and salt.
    public string CreateHash(string password, string salt)
    {
        // Get a byte array containing the combined password + salt.
        string authDetails = password + salt;
        byte[] authBytes = System.Text.Encoding.ASCII.GetBytes(authDetails);
    
        // Use MD5 to compute the hash of the byte array, and return the hash as
        // a Base64-encoded string.
        var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] hashedBytes = md5.ComputeHash(authBytes);
        string hash = Convert.ToBase64String(hashedBytes);
    
        return hash;
    }
    
    // Check to see if the given password and salt hash to the same value
    // as the given hash.
    public bool IsMatchingHash(string password, string salt, string hash)
    {
        // Recompute the hash from the given auth details, and compare it to
        // the hash provided by the cookie.
        return CreateHash(password, salt) == hash;
    }
    
    // Create an authentication cookie that stores the username and a hash of
    // the password and salt.
    public HttpCookie CreateAuthCookie(string username, string password, string salt)
    {
        // Create the cookie and set its value to the username and a hash of the
        // password and salt. Use a pipe character as a delimiter so we can
        // separate these two elements later.
        HttpCookie cookie = new HttpCookie("YourSiteCookieNameHere");
        cookie.Value = username + "|" + CreateHash(password, salt);
        return cookie;
    }
    
    // Determine whether the given authentication cookie is valid by
    // extracting the username, retrieving the saved password, recomputing its
    // hash, and comparing the hashes to see if they match. If they match,
    // then this authentication cookie is valid.
    public bool IsValidAuthCookie(HttpCookie cookie, string salt)
    {
        // Split the cookie value by the pipe delimiter.
        string[] values = cookie.Value.Split('|');
        if (values.Length != 2) return false;
    
        // Retrieve the username and hash from the split values.
        string username = values[0];
        string hash = values[1];
    
        // You'll have to provide your GetPasswordForUser function.
        string password = GetPasswordForUser(username);
    
        // Check the password and salt against the hash.
        return IsMatchingHash(password, salt, hash);
    }

    More details, you could refer to this answer:

    https://stackoverflow.com/a/3355868/7609093 

    Best Regards,

    Brando

    Friday, May 11, 2018 7:21 AM