2010-07-28 9 views
5

ho implementato ricordati di me opzione nel mio asp.net moduli elettronici utilizzando questo,asp.net "Ricordati di me" cookie

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

sto facendo nel modo giusto? Qualsiasi suggerimento .. Sto usando l'autenticazione di Windows e sono not using asp.net membership ..

risposta

11

Invece di memorizzare direttamente il nome utente e la password nel cookie, memorizzare il nome utente e un hash della password e un sale nel cookie, quindi quando si autentica il cookie, recuperare la password per il nome utente specificato, ricreare l'hash con la password e lo stesso sale e confrontarli.

Creare l'hash è semplice come memorizzare la password e i valori saltati in una stringa, convertire la stringa in un array di byte, calcolare l'hash dell'array di byte (usando MD5 o qualsiasi altra cosa si preferisca) e convertire l'hash risultante a una stringa (probabilmente tramite codifica base64).

Ecco qualche esempio di codice:

// 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); 
} 
+0

@Erik ho incluso tutti questi in una classe .. Come usarli sul mio pulsante? –

+1

Immagino tu intenda il tuo pulsante di accesso: in tal caso, prendi semplicemente il nome utente e la password come di solito, chiama il metodo "CreateAuthCookie" passando il nome utente, la password e il sale (che in realtà è solo una stringa qualsiasi, a lungo come si utilizza lo stesso per ogni chiamata di metodo) - quindi fare ciò che si desidera con il cookie restituito dal metodo. –

+1

Quando arriva il momento di vedere se l'utente ha già effettuato l'accesso, è sufficiente trovare il cookie in base al nome ("YourSiteCookieNameHere") e chiamare il metodo "IsValidAuthCookie" per confrontare i valori in quel cookie con i dati di autenticazione effettivi memorizzati nel Banca dati. Non dimenticare di usare lo stesso sale. –

4

Non memorizzerei la password degli utenti in un cookie ... Piuttosto memorizzare l'ID utente e l'indirizzo IP nel cookie.

+4

l'uso deve effettuare nuovamente il login se l'utente si sposta dall'ufficio/casa wifi –

+0

non è il lavoro più grande intorno a –

0

non avrei memorizzare l'id ip/utente nel cookie. Il sequestro di sessione sarebbe quindi molto semplice, cioè conosco il nome utente/ip dei miei colleghi, potrei aggiungere quel cookie al mio messaggio e poi potrò lavorare alla sessione del mio collega.

Problemi correlati