asp.net печенье "Запомнить меня" - PullRequest
5 голосов
/ 28 июля 2010

Я реализовал опцию Запомнить меня в моей веб-форме asp.net, используя это,

protected void LBtnSubmit_Click(object sender, EventArgs e)
 {
  if (this.ChkRememberme != null && this.ChkRememberme.Checked == true)
  {
     HttpCookie cookie = new HttpCookie(TxtUserName.Text, TxtPassword.Text);
     cookie.Expires.AddYears(1);
     Response.Cookies.Add(cookie);
  }
}

Я делаю это правильно? Любое предложение .. Я использую проверку подлинности Windows, и я not using asp.net membership ..

Ответы [ 3 ]

12 голосов
/ 28 июля 2010

Вместо того, чтобы непосредственно сохранять имя пользователя и пароль в cookie, сохраните имя пользователя и хеш пароля и соль в cookie, затем, когда вы аутентифицируете cookie, получите пароль для данного имени пользователя, заново создайте хеш с паролем и той же солью и сравни их.

Создание хеша так же просто, как хранение пароля и значений соли вместе в строке, преобразование строки в байтовый массив, вычисление хеша байтового массива (с использованием MD5 или любого другого значения) и преобразование полученного хеша в строка (вероятно, с помощью кодировки base64).

Вот пример кода:

// 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);
}
4 голосов
/ 28 июля 2010

Я бы не стал хранить пароль пользователя в cookie-файле ... Скорее хранить идентификатор пользователя и IP-адрес в cookie-файле.

0 голосов
/ 17 апреля 2013

Я бы не стал хранить ip / user id в куки.Тогда хай-джэкджинг сессий будет действительно легким, я имею в виду, что я знаю имя пользователя / ip моих коллег, я могу добавить этот файл cookie в свое сообщение, и тогда я смогу работать на сессии моего коллеги.

...