<blockquote>
<h4>Moderator note:</h4>
<p>This question is not a good fit for our question and answer format with the <a href="/help/on-topic">topicality rules</a> which currently apply for Stack Overflow. We normally use a &quot;historical lock&quot; for such questions where the content still has value. However, the answers on this question are actively maintained and a historical lock doesn't permit editing of the answers. As such, a &quot;wiki answer&quot; lock has been applied to allow the answers to be edited. You should assume the topicality issues which are normally handled by a historical lock are present (i.e. this question not a good example of an on-topic question for Stack Overflow).</p>
</blockquote>
<h2>Form-based authentication for websites</h2>
<p>We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. &quot;Form based authentication for websites&quot; should be a fine topic for such an experiment.</p>
<h3>It should include topics such as:</h3>
<ul>
<li>How to log in</li>
<li>How to log out</li>
<li>How to remain logged in</li>
<li>Managing cookies (including recommended settings)</li>
<li>SSL/HTTPS encryption</li>
<li>How to store passwords</li>
<li>Using secret questions</li>
<li>Forgotten username/password functionality</li>
<li>Use of <a href="https://en.wikipedia.org/wiki/Cryptographic_nonce" rel="nofollow noreferrer">nonces</a> to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">cross-site request forgeries (CSRF)</a></li>
<li><a href="http://openid.net/" rel="nofollow noreferrer">OpenID</a></li>
<li>&quot;Remember me&quot; checkbox</li>
<li>Browser autocompletion of usernames and passwords</li>
<li>Secret URLs (public <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> protected by digest)</li>
<li>Checking password strength</li>
<li>E-mail validation</li>
<li><em>and much more about</em> <a href="http://en.wikipedia.org/wiki/Form-based_authentication" rel="nofollow noreferrer">form based authentication</a>...</li>
</ul>
<h3>It should not include things like:</h3>
<ul>
<li>Roles and authorization</li>
<li>HTTP basic authentication</li>
</ul>
<h3>Please help us by:</h3>
<ol>
<li>Suggesting subtopics</li>
<li>Submitting good articles about this subject</li>
<li>Editing the official answer</li>
</ol>

[{'answer_id': 555, 'author': 'Michiel de Mare', 'author_id': 136, 'author_profile': 'https://Stackoverflow.com/users/136', 'pm_score': 9, 'selected': False, 'text': '<h1>Definitive Article</h1>\n\n<h3>Sending credentials</h3>\n\n<p>The only practical way to send credentials 100% securely is by using <a href="http://en.wikipedia.org/wiki/SSL" rel="noreferrer">SSL</a>. Using JavaScript to hash the password is not safe. Common pitfalls for client-side password hashing:</p>\n\n<ul>\n<li>If the connection between the client and server is unencrypted, everything you do is <a href="https://stackoverflow.com/questions/14907581/ssl-and-man-in-the-middle-misunderstanding">vulnerable to man-in-the-middle attacks</a>. An attacker could replace the incoming javascript to break the hashing or send all credentials to their server, they could listen to client responses and impersonate the users perfectly, etc. etc. SSL with trusted Certificate Authorities is designed to prevent MitM attacks.</li>\n<li>The hashed password received by the server is <a href="https://security.stackexchange.com/questions/45254/owasp-recommendation-on-client-side-password-hashing">less secure</a> if you don\'t do additional, redundant work on the server.</li>\n</ul>\n\n<p>There\'s another secure method called <strong>SRP</strong>, but it\'s patented (although it is <a href="http://srp.stanford.edu/license.txt" rel="noreferrer">freely licensed</a>) and there are few good implementations available.</p>\n\n<h3>Storing passwords</h3>\n\n<p>Don\'t ever store passwords as plaintext in the database. Not even if you don\'t care about the security of your own site. Assume that some of your users will reuse the password of their online bank account. So, store the hashed password, and throw away the original. And make sure the password doesn\'t show up in access logs or application logs. OWASP <a href="https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet#Impose_infeasible_verification_on_attacker" rel="noreferrer">recommends the use of Argon2</a> as your first choice for new applications. If this is not available, PBKDF2 or scrypt should be used instead. And finally if none of the above are available, use bcrypt.</p>\n\n<p>Hashes by themselves are also insecure. For instance, identical passwords mean identical hashes--this makes hash lookup tables an effective way of cracking lots of passwords at once. Instead, store the <strong>salted</strong> hash. A salt is a string appended to the password prior to hashing - use a different (random) salt per user. The salt is a public value, so you can store them with the hash in the database. See <a href="http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right" rel="noreferrer">here</a> for more on this.</p>\n\n<p>This means that you can\'t send the user their forgotten passwords (because you only have the hash). Don\'t reset the user\'s password unless you have authenticated the user (users must prove that they are able to read emails sent to the stored (and validated) email address.)</p>\n\n<h3>Security questions</h3>\n\n<p>Security questions are insecure - avoid using them. Why? Anything a security question does, a password does better. Read <strong><em>PART III: Using Secret Questions</em></strong> in <a href="http://srp.stanford.edu/license.txt" rel="noreferrer">@Jens Roland answer</a> here in this wiki.</p>\n\n<h3>Session cookies</h3>\n\n<p>After the user logs in, the server sends the user a session cookie. The server can retrieve the username or id from the cookie, but nobody else can generate such a cookie (TODO explain mechanisms).</p>\n\n<p><a href="http://en.wikipedia.org/wiki/Session_hijacking" rel="noreferrer">Cookies can be hijacked</a>: they are only as secure as the rest of the client\'s machine and other communications. They can be read from disk, sniffed in network traffic, lifted by a cross-site scripting attack, phished from a poisoned DNS so the client sends their cookies to the wrong servers. Don\'t send persistent cookies. Cookies should expire at the end of the client session (browser close or leaving your domain).</p>\n\n<p>If you want to autologin your users, you can set a persistent cookie, but it should be distinct from a full-session cookie. You can set an additional flag that the user has auto-logged in, and needs to log in for real for sensitive operations. This is popular with shopping sites that want to provide you with a seamless, personalized shopping experience but still protect your financial details. For example, when you return to visit Amazon, they show you a page that looks like you\'re logged in, but when you go to place an order (or change your shipping address, credit card etc.), they ask you to confirm your password.</p>\n\n<p>Financial websites such as banks and credit cards, on the other hand, only have sensitive data and should not allow auto-login or a low-security mode.</p>\n\n<h3>List of external resources</h3>\n\n<ul>\n<li><a href="http://pdos.csail.mit.edu/papers/webauth:sec10.pdf" rel="noreferrer">Dos and Don\'ts of Client Authentication on the Web (PDF)</a><br>\n21 page academic article with many great tips.  </li>\n<li><a href="http://news.ycombinator.com/item?id=205572" rel="noreferrer">Ask YC: Best Practices for User Authentication</a><br>\nForum discussion on the subject  </li>\n<li><a href="http://www.codinghorror.com/blog/archives/000953.html" rel="noreferrer">You\'re Probably Storing Passwords Incorrectly</a><br>\nIntroductory article about storing passwords</li>\n<li><a href="http://news.ycombinator.com/item?id=55660" rel="noreferrer">Discussion: Coding Horror: You\'re Probably Storing Passwords Incorrectly</a><br>\nForum discussion about a Coding Horror article.</li>\n<li>Never store passwords in a database!<br>\nAnother warning about storing passwords in the database.</li>\n<li><a href="http://en.wikipedia.org/wiki/Password_cracking" rel="noreferrer">Password cracking</a><br>\nWikipedia article on weaknesses of several password hashing schemes.</li>\n<li><a href="http://www.securityfocus.com/blogs/262" rel="noreferrer">Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes</a><br>\nDiscussion about rainbow tables and how to defend against them, and against other threads. Includes extensive discussion.</li>\n</ul>\n'}, {'answer_id': 477578, 'author': 'Jens Roland', 'author_id': 57068, 'author_profile': 'https://Stackoverflow.com/users/57068', 'pm_score': 13, 'selected': True, 'text': '<h2>PART I: How To Log In</h2>\n<p>We\'ll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.</p>\n<p><strong>To HTTPS or not to HTTPS?</strong></p>\n<p>Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won\'t address \'owned\' wires other than to say this: Just use HTTPS.</p>\n<p>In essence, the only <strong>practical</strong> way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, <a href="https://en.wikipedia.org/wiki/Transport_Layer_Security" rel="noreferrer">TLS</a>) or a proven &amp; tested challenge-response scheme (for example, the <a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange" rel="noreferrer">Diffie-Hellman</a>-based SRP). <em>Any other method can be easily circumvented</em> by an eavesdropping attacker.</p>\n<p>Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical \'cold war style\' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it\'s hard to imagine that a dev would be willing to implement two-factor auth but not SSL.</p>\n<p><strong>(Do not) Roll-your-own JavaScript encryption/hashing</strong></p>\n<p>Given the perceived (though now <a href="https://letsencrypt.org/" rel="noreferrer">avoidable</a>) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire.</p>\n<p>While this is a noble thought, it is essentially useless (and can be a <a href="https://stackoverflow.com/questions/1380168/does-it-make-security-sense-to-hash-password-on-client-end">security flaw</a>) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don\'t know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security).</p>\n<p>While it is true that hashing the password <em>can be</em> effective against <strong>password disclosure</strong>, it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).</p>\n<p><strong>CAPTCHAS against humanity</strong></p>\n<p><a href="https://en.wikipedia.org/wiki/CAPTCHA" rel="noreferrer">CAPTCHA</a> is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don\'t require a CAPTCHA, specifically properly designed server-side login throttling schemes - we\'ll discuss those later.</p>\n<p>Know that CAPTCHA implementations are not created alike; they often aren\'t human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to <a href="https://en.wikipedia.org/wiki/OWASP" rel="noreferrer">OWASP</a>, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a>). If you must use a CAPTCHA, use Google\'s <a href="https://en.wikipedia.org/wiki/ReCAPTCHA" rel="noreferrer">reCAPTCHA</a>, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly.</p>\n<p>Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.</p>\n<p><strong>Storing Passwords / Verifying logins</strong></p>\n<p>This may finally be common knowledge after all the highly-publicized hacks and user data leaks we\'ve seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security.</p>\n<p>So if you can\'t store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a <a href="https://en.wikipedia.org/wiki/Key_derivation_function" rel="noreferrer">key derivation function</a>. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password (&quot;correcthorsebatterystaple&quot;) into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this <a href="https://security.stackexchange.com/a/31846/8340">article</a> on sec.stackexchange for more detailed information.</p>\n<p>The reason a salt is used is that hashing in itself is not sufficient -- you\'ll want to add a so-called \'salt\' to protect the hash against <a href="https://en.wikipedia.org/wiki/Rainbow_table" rel="noreferrer">rainbow tables</a>. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack.</p>\n<p>A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively <a href="https://en.wikipedia.org/wiki/Key_stretching" rel="noreferrer">&quot;stretch the key&quot;</a>, which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.</p>\n<p><strong>Session data - &quot;You are logged in as Spiderman69&quot;</strong></p>\n<p>Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.</p>\n<blockquote>\n<p>If you are unfamiliar with session data, here\'s how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already.</p>\n</blockquote>\n<p>If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent <a href="https://owasp.org/www-community/attacks/Session_fixation" rel="noreferrer">session fixation</a>.</p>\n<p>Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).</p>\n<h2>PART II: How To Remain Logged In - The Infamous &quot;Remember Me&quot; Checkbox</h2>\n<p>Persistent Login Cookies (&quot;remember me&quot; functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them.</p>\n<p>Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It\'s not like we go to our user\'s houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either.</p>\n<p>Of course, some systems can\'t afford to have <em>any</em> accounts hacked; for such systems, there is no way you can justify having persistent logins.</p>\n<p><strong>If you DO decide to implement persistent login cookies, this is how you do it:</strong></p>\n<ol>\n<li><p>First, take some time to read <a href="https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence" rel="noreferrer">Paragon Initiative\'s article</a> on the subject. You\'ll need to get a bunch of elements right, and the article does a great job of explaining each.</p>\n</li>\n<li><p>And just to reiterate one of the most common pitfalls, <strong>DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT!</strong> The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to <a href="https://security.stackexchange.com/a/63438/5002">https://security.stackexchange.com/a/63438/5002</a> a weak hash will do just fine for this purpose) when storing persistent login tokens.</p>\n</li>\n</ol>\n<h2>PART III: Using Secret Questions</h2>\n<p><strong>Don\'t implement \'secret questions\'</strong>. The \'secret questions\' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... &quot;Wasilla High School&quot;!</p>\n<p>Even with user-specified questions, it is highly likely that most users will choose either:</p>\n<ul>\n<li><p>A \'standard\' secret question like mother\'s maiden name or favorite pet</p>\n</li>\n<li><p>A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar</p>\n</li>\n<li><p>Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine</p>\n</li>\n</ul>\n<p><strong>In conclusion, security questions are inherently insecure in virtually all their forms and variations, and should not be employed in an authentication scheme for any reason.</strong></p>\n<p>The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can\'t access their email to get to a reactivation code. This at the expense of security and Sarah Palin\'s reputation. Worth it? Probably not.</p>\n<h2>PART IV: Forgotten Password Functionality</h2>\n<p>I already mentioned why you should <strong>never use security questions</strong> for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:</p>\n<ol>\n<li><p>Don\'t <em>reset</em> a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).</p>\n</li>\n<li><p>Always hash the lost password code/token in the database. <em><strong>AGAIN</strong></em>, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user\'s email address, then hash it, save the hash in your database -- and <em>throw away the original</em>. Just like a password or a persistent login token.</p>\n</li>\n</ol>\n<p>A final note: always make sure your interface for entering the \'lost password code\' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long \'lost password codes\' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.</p>\n<h2>PART V: Checking Password Strength</h2>\n<p>First, you\'ll want to read this small article for a reality check: <a href="http://www.whatsmypass.com/?p=415" rel="noreferrer">The 500 most common passwords</a></p>\n<p>Okay, so maybe the list isn\'t the <em>canonical</em> list of most common passwords on <em>any</em> system <em>anywhere ever</em>, but it\'s a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords.</p>\n<p>So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable.</p>\n<p>Thwarting this requires calculating the entropy of a password and then applying a threshold.  The National Institute of Standards and Technology (NIST) <a href="https://en.wikipedia.org/wiki/Password_strength#NIST_Special_Publication_800-63" rel="noreferrer">Special Publication 800-63</a> has a set of very good suggestions.  That, when combined with a dictionary and keyboard layout analysis (for example, \'qwertyuiop\' is a bad password), can <a href="https://cubicspot.blogspot.com/2012/01/how-to-calculate-password-strength-part.html" rel="noreferrer">reject 99% of all poorly selected passwords</a> at a level of 18 bits of entropy.  Simply calculating password strength and <a href="https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" rel="noreferrer">showing a visual strength meter</a> to a user is good, but insufficient.  Unless it is enforced, a lot of users will most likely ignore it.</p>\n<p>And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe\'s <a href="https://xkcd.com/936/" rel="noreferrer">Password Strength xkcd</a> is highly recommended.</p>\n<p>Utilize Troy Hunt\'s <a href="https://haveibeenpwned.com/API/" rel="noreferrer">Have I Been Pwned API</a> to check users passwords against passwords compromised in public data breaches.</p>\n<h2>PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts</h2>\n<p>First, have a look at the numbers: <a href="https://www.lockdown.co.uk/?pg=combi&amp;s=articles" rel="noreferrer">Password Recovery Speeds - How long will your password stand up</a></p>\n<p>If you don\'t have the time to look through the tables in that link, here\'s the list of them:</p>\n<ol>\n<li><p>It takes <em>virtually no time</em> to crack a weak password, even if you\'re cracking it with an abacus</p>\n</li>\n<li><p>It takes <em>virtually no time</em> to crack an alphanumeric 9-character password if it is <strong>case insensitive</strong></p>\n</li>\n<li><p>It takes <em>virtually no time</em> to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is <strong>less than 8 characters long</strong> (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)</p>\n</li>\n<li><p><strong>It would, however, take an inordinate amount of time to crack even a 6-character password, <em>if you were limited to one attempt per second!</em></strong></p>\n</li>\n</ol>\n<p>So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the <em>brute force</em> attack) really isn\'t that difficult. But preventing it <em>right</em> isn\'t as easy as it seems.</p>\n<p>Generally speaking, you have three choices that are all effective against brute-force attacks <em>(and dictionary attacks, but since you are already employing a strong passwords policy, they shouldn\'t be an issue)</em>:</p>\n<ul>\n<li><p>Present a <strong>CAPTCHA</strong> after N failed attempts (annoying as hell and often ineffective -- but I\'m repeating myself here)</p>\n</li>\n<li><p><strong>Locking accounts</strong> and requiring email verification after N failed attempts (this is a <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack" rel="noreferrer">DoS</a> attack waiting to happen)</p>\n</li>\n<li><p>And finally, <strong>login throttling</strong>: that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off).</p>\n</li>\n</ul>\n<p><strong>Best practice #1:</strong> A short time delay that increases with the number of failed attempts, like:</p>\n<ul>\n<li>1 failed attempt = no delay</li>\n<li>2 failed attempts = 2 sec delay</li>\n<li>3 failed attempts = 4 sec delay</li>\n<li>4 failed attempts = 8 sec delay</li>\n<li>5 failed attempts = 16 sec delay</li>\n<li>etc.</li>\n</ul>\n<p>DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.</p>\n<blockquote>\n<p>To clarify: The delay is <em>not</em> a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase.</p>\n</blockquote>\n<p><strong>Best practice #2:</strong> A medium length time delay that goes into effect after N failed attempts, like:</p>\n<ul>\n<li>1-4 failed attempts = no delay</li>\n<li>5 failed attempts = 15-30 min delay</li>\n</ul>\n<p>DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you.</p>\n<p><strong>Best practice #3:</strong> Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:</p>\n<ul>\n<li>1-4 failed attempts = no delay</li>\n<li>5+ failed attempts = 20 sec delay</li>\n</ul>\n<p>Or, an increasing delay with a fixed upper bound, like:</p>\n<ul>\n<li>1 failed attempt = 5 sec delay</li>\n<li>2 failed attempts = 15 sec delay</li>\n<li>3+ failed attempts = 45 sec delay</li>\n</ul>\n<p>This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.</p>\n<blockquote>\n<p><em>As a rule of thumb, however, I would say: the stronger your password policy is, the less you have to bug users with delays. If you require strong (case-sensitive alphanumerics + required numbers and symbols) 9+ character passwords, you could give the users 2-4 non-delayed password attempts before activating the throttling.</em></p>\n</blockquote>\n<p>DoS attacking this final login throttling scheme would be <em><strong>very</strong></em> impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won\'t even be delayed <em>while the attack is in progress</em>. That way, the very impractical DoS attack becomes an <em>extremely</em> impractical attack.</p>\n<p>Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points</p>\n<h2>PART VII: Distributed Brute Force Attacks</h2>\n<p>Just as an aside, more advanced attackers will try to circumvent login throttling by \'spreading their activities\':</p>\n<ul>\n<li><p>Distributing the attempts on a botnet to prevent IP address flagging</p>\n</li>\n<li><p>Rather than picking one user and trying the 50.000 most common passwords (which they can\'t, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995</p>\n</li>\n<li><p>Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar</p>\n</li>\n</ul>\n<p>Here, the best practice would be <strong>logging the number of failed logins, system-wide</strong>, and using a running average of your site\'s bad-login frequency as the basis for an upper limit that you then impose on all users.</p>\n<p>Too abstract? Let me rephrase:</p>\n<p>Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins).</p>\n<p>I also posted a question with <a href="https://stackoverflow.com/questions/479233/what-is-the-best-distributed-brute-force-countermeasure">more details and a really good discussion of how to avoid tricky pitfals</a> in fending off distributed brute force attacks</p>\n<h2>PART VIII: Two-Factor Authentication and Authentication Providers</h2>\n<p>Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites.  Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services.</p>\n<p>Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.</p>\n<h2>MUST-READ LINKS About Web Authentication</h2>\n<ol>\n<li><a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Guide To Authentication</a> / <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a></li>\n<li><a href="https://pdos.csail.mit.edu/papers/webauth:sec10.pdf" rel="noreferrer">Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)</a></li>\n<li><a href="https://en.wikipedia.org/wiki/HTTP_cookie#Drawbacks_of_cookies" rel="noreferrer">Wikipedia: HTTP cookie</a></li>\n<li><a href="https://cups.cs.cmu.edu/soups/2008/proceedings/p13Rabkin.pdf" rel="noreferrer">Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)</a></li>\n</ol>\n'}, {'answer_id': 6984591, 'author': 'Charlie', 'author_id': 139320, 'author_profile': 'https://Stackoverflow.com/users/139320', 'pm_score': 7, 'selected': False, 'text': '<p>First, a strong caveat that this answer is not the best fit for this exact question. It should definitely not be the top answer!</p>\n\n<p>I will go ahead and mention Mozilla’s proposed <a href="https://browserid.org/" rel="noreferrer">BrowserID</a> (or perhaps more precisely, the <a href="https://wiki.mozilla.org/Identity/Verified_Email_Protocol/Latest" rel="noreferrer">Verified Email Protocol</a>) in the spirit of finding an upgrade path to better approaches to authentication in the future.</p>\n\n<p>I’ll summarize it this way:</p>\n\n<ol>\n<li>Mozilla is a nonprofit with <a href="http://www.mozilla.org/about/manifesto.en.html" rel="noreferrer">values</a> that align well with finding good solutions to this problem.</li>\n<li>The reality today is that most websites use form-based authentication</li>\n<li>Form-based authentication has a big drawback, which is an increased risk of <a href="http://en.wikipedia.org/wiki/Phishing" rel="noreferrer">phishing</a>. Users are asked to enter sensitive information into an area controlled by a remote entity, rather than an area controlled by their User Agent (browser).</li>\n<li>Since browsers are implicitly trusted (the whole idea of a User Agent is to act on behalf of the User), they can help improve this situation.</li>\n<li>The primary force holding back progress here is <a href="http://www.w3.org/2011/identity-ws/papers/idbrowser2011_submission_10.pdf" rel="noreferrer">deployment deadlock</a>. Solutions must be decomposed into steps which provide some incremental benefit on their own.</li>\n<li>The simplest decentralized method for expressing an identity that is built into the internet infrastructure is the domain name.</li>\n<li>As a second level of expressing identity, each domain manages its own set of accounts.</li>\n<li>The form “account<code>@</code>domain” is concise and supported by a wide range of protocols and URI schemes. Such an identifier is, of course, most universally recognized as an email address.</li>\n<li>Email providers are already the de-facto primary identity providers online. Current password reset flows usually let you take control of an account if you can prove that you control that account’s associated email address.</li>\n<li>The Verified Email Protocol was proposed to provide a secure method, based on public key cryptography, for streamlining the process of proving to domain B that you have an account on domain A.</li>\n<li>For browsers that don’t support the Verified Email Protocol (currently all of them), Mozilla provides a shim which implements the protocol in client-side JavaScript code.</li>\n<li>For email services that don’t support the Verified Email Protocol, the protocol allows third parties to act as a trusted intermediary, asserting that they’ve verified a user’s ownership of an account. It is not desirable to have a large number of such third parties; this capability is intended only to allow an upgrade path, and it is much preferred that email services provide these assertions themselves.</li>\n<li>Mozilla offers their own service to act like such a trusted third party. Service Providers (that is, Relying Parties) implementing the Verified Email Protocol may choose to trust Mozilla\'s assertions or not. Mozilla’s service verifies users’ account ownership using the conventional means of sending an email with a confirmation link.</li>\n<li>Service Providers may, of course, offer this protocol as an option in addition to any other method(s) of authentication they might wish to offer.</li>\n<li>A big user interface benefit being sought here is the “identity selector”. When a user visits a site and chooses to authenticate, their browser shows them a selection of email addresses (“personal”, “work”, “political activism”, etc.) they may use to identify themselves to the site.</li>\n<li>Another big user interface benefit being sought as part of this effort is <a href="https://wiki.mozilla.org/Identity/Verified_Email_Protocol/Latest-Session" rel="noreferrer">helping the browser know more about the user’s session</a> – who they’re signed in as currently, primarily – so it may display that in the browser chrome.</li>\n<li>Because of the distributed nature of this system, it avoids lock-in to major sites like Facebook, Twitter, Google, etc. Any individual can own their own domain and therefore act as their own identity provider.</li>\n</ol>\n\n<p>This is not strictly “form-based authentication for websites”. But it is an effort to transition from the current norm of form-based authentication to something more secure: browser-supported authentication.</p>\n'}, {'answer_id': 6985280, 'author': 'lifeisstillgood', 'author_id': 571567, 'author_profile': 'https://Stackoverflow.com/users/571567', 'pm_score': 6, 'selected': False, 'text': '<p>I do not think the above answer is "wrong" but there are large areas of authentication that are not touched upon (or rather the emphasis is on "how to implement cookie sessions", not on "what options are available and what are the trade-offs".</p>\n\n<p>My suggested edits/answers are</p>\n\n<ul>\n<li>The problem lies more in account setup than in password checking.</li>\n<li>The use of two-factor authentication is much more secure than more clever means of password encryption</li>\n<li><p>Do NOT try to implement your own login form or database storage of passwords, unless \nthe data being stored is valueless at account creation and self-generated (that is, web 2.0 style like Facebook, <a href="http://en.wikipedia.org/wiki/Flickr" rel="noreferrer">Flickr</a>, etc.)</p>\n\n<ol>\n<li>Digest Authentication is a standards-based approach supported in all major browsers and servers, that will not send a password even over a secure channel.</li>\n</ol></li>\n</ul>\n\n<p>This avoids any need to have "sessions" or cookies as the browser itself will re-encrypt the communication each time. It is the most "lightweight" development approach.</p>\n\n<p>However, I do not recommend this, except for public, low-value services. This is an issue with some of the other answers above - do not try an re-implement server-side authentication mechanisms - this problem has been solved and is supported by most major browsers. Do not use cookies. Do not store anything in your own hand-rolled database. Just ask, per request, if the request is authenticated. Everything else should be supported by configuration and third-party trusted software.</p>\n\n<p>So ...</p>\n\n<p>First, we are confusing the initial creation of an account (with a password) with the re-checking of the password subsequently. If I am Flickr and creating your site for the first time, the new user has access to zero value (blank web space). I truly do not care if the person creating the account is lying about their name. If I am creating an account of the hospital intranet/extranet, the value lies in all the medical records, and so I <em>do</em> care about the identity (*) of the account creator.</p>\n\n<p>This is the very very hard part. The <em>only</em> decent solution is a web of trust. For example, you join the hospital as a doctor. You create a web page hosted somewhere with your photo, your passport number, and a public key, and hash them all with the private key. You then visit the hospital and the system administrator looks at your passport, sees if the photo matches you, and then hashes the web page/photo hash with the hospital private key. From now on we can securely exchange keys and tokens. As can anyone who trusts the hospital (there is the secret sauce BTW). The system administrator can also give you an <a href="http://en.wikipedia.org/wiki/RSA_%28security_firm%29" rel="noreferrer">RSA</a> dongle or other two-factor authentication.</p>\n\n<p>But this is a <em>lot</em> of a hassle, and not very web 2.0. However, it is the only secure way to create new accounts that have access to valuable information that is not self-created.</p>\n\n<ol>\n<li><p>Kerberos and SPNEGO - single sign-on mechanisms with a trusted third party - basically the user verifies against a trusted third party. (NB this is not in any way the not to be trusted <a href="http://en.wikipedia.org/wiki/OAuth" rel="noreferrer">OAuth</a>)</p></li>\n<li><p><a href="http://en.wikipedia.org/wiki/Secure_Remote_Password_protocol" rel="noreferrer">SRP</a> - sort of clever password authentication without a trusted third party. But here we are getting into the realms of "it\'s safer to use two-factor authentication, even if that\'s costlier"</p></li>\n<li><p><a href="http://en.wikipedia.org/wiki/SSL" rel="noreferrer">SSL</a> client side - give the clients a public key certificate (support in all major browsers - but raises questions over client machine security).</p></li>\n</ol>\n\n<p>In the end, it\'s a tradeoff - what is the cost of a security breach vs the cost of implementing more secure approaches. One day, we may see a proper <a href="http://en.wikipedia.org/wiki/Public-key_infrastructure" rel="noreferrer">PKI</a> widely accepted and so no more own rolled authentication forms and databases. One day...</p>\n'}, {'answer_id': 6989665, 'author': 'josh', 'author_id': 884964, 'author_profile': 'https://Stackoverflow.com/users/884964', 'pm_score': 6, 'selected': False, 'text': "<p>When hashing, don't use fast hash algorithms such as MD5 (many hardware implementations exist).  Use something like SHA-512.  For passwords, slower hashes are better.</p>\n\n<p>The faster you can create hashes, the faster any brute force checker can work. Slower hashes will therefore slow down brute forcing. A slow hash algorithm will make brute forcing impractical for longer passwords (8 digits +)</p>\n"}, {'answer_id': 10701801, 'author': 'Pieter888', 'author_id': 192310, 'author_profile': 'https://Stackoverflow.com/users/192310', 'pm_score': 7, 'selected': False, 'text': '<p>I just thought I\'d share this solution that I found to be working just fine.</p>\n<p>I call it the <strong>Dummy Field</strong> (though I haven\'t invented this so don\'t credit me). Others know this as a honey pot.</p>\n<p>In short: you just have to insert this into your <code>&lt;form&gt;</code> and check for it to be empty at when validating:</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;email&quot; style=&quot;display:none&quot; /&gt;\n</code></pre>\n<p>The trick is to fool a bot into thinking it has to insert data into a required field, that\'s why I named the input &quot;email&quot;. If you already have a field called email that you\'re using you should try naming the dummy field something else like &quot;company&quot;, &quot;phone&quot; or &quot;emailaddress&quot;. Just pick something you know you don\'t need and what sounds like something people would normally find logical to fill in into a web form. Now hide the <code>input</code> field using CSS or JavaScript/jQuery - whatever fits you best - just <strong>don\'t</strong> set the input <code>type</code> to <code>hidden</code> or else the bot won\'t fall for it.</p>\n<p>When you are validating the form (either client or server side) check if your dummy field has been filled to determine if it was sent by a human or a bot.</p>\n<p>Example:</p>\n<p><strong>In case of a human:</strong>\nThe user will not see the dummy field (in my case named &quot;email&quot;) and will not attempt to fill it. So the value of the dummy field should still be empty when the form has been sent.</p>\n<p><strong>In case of a bot:</strong> The bot will see a field whose type is <code>text</code> and a name <code>email</code> (or whatever it is you called it) and will logically attempt to fill it with appropriate data. It doesn\'t care if you styled the input form with some fancy CSS, web-developers do it all the time. Whatever the value in the dummy field is, we don\'t care as long as it\'s larger than <code>0</code> characters.</p>\n<p>I used this method on a guestbook in combination with <a href="http://en.wikipedia.org/wiki/CAPTCHA" rel="nofollow noreferrer">CAPTCHA</a>, and I haven\'t seen a single spam post since. I had used a CAPTCHA-only solution before, but eventually, it resulted in about five spam posts every hour. Adding the dummy field in the form has stopped (at least until now) all the spam from appearing.</p>\n<p>I believe this can also be used just fine with a login/authentication form.</p>\n<p><strong>Warning</strong>: Of course this method is not 100% foolproof. Bots can be programmed to ignore input fields with the style <code>display:none</code> applied to it. You also have to think about people who use some form of auto-completion (like most browsers have built-in!) to auto-fill all form fields for them. They might just as well pick up a dummy field.</p>\n<p>You can also vary this up a little by leaving the dummy field visible but outside the boundaries of the screen, but this is totally up to you.</p>\n<p>Be creative!</p>\n'}, {'answer_id': 13545692, 'author': 'pixeline', 'author_id': 53960, 'author_profile': 'https://Stackoverflow.com/users/53960', 'pm_score': 6, 'selected': False, 'text': '<p>My favourite rule in regards to authentication systems: use passphrases, not passwords. Easy to remember, hard to crack.\nMore info: <a href="http://www.codinghorror.com/blog/2005/07/passwords-vs-pass-phrases.html" rel="nofollow noreferrer">Coding Horror: Passwords vs. Pass Phrases</a></p>\n'}, {'answer_id': 29932630, 'author': 'Mike Robinson', 'author_id': 4811873, 'author_profile': 'https://Stackoverflow.com/users/4811873', 'pm_score': 4, 'selected': False, 'text': '<p>I would like to add one very important comment: -</p>\n\n<ul>\n<li>"In a <em>corporate,</em> <strong>intra-</strong> net setting," most if not all of the foregoing might not apply!</li>\n</ul>\n\n<p>Many corporations deploy "internal use only" websites which are, effectively, "corporate applications" that happen to have been implemented through URLs. These URLs can <em>(supposedly ...)</em> only be resolved within "the company\'s internal network." <em>(Which network magically includes all VPN-connected \'road warriors.\')</em> </p>\n\n<p>When a user is dutifully-connected to the aforesaid network, their identity <em>("authentication")</em> is [already ...] "conclusively known," as is their permission <em>("authorization")</em> to do certain things ... such as ... "to access this website."</p>\n\n<p>This "authentication + authorization" service can be provided by several different technologies, such as LDAP <em>(Microsoft OpenDirectory)</em>, or Kerberos.</p>\n\n<p>From your point-of-view, you simply know this: that <em>anyone</em> who legitimately winds-up at your website <em>must</em> be accompanied by [an environment-variable magically containing ...] a "token." (<em>i.e.</em> The absence of such a token must be immediate grounds for <code>404 Not Found</code>.)</p>\n\n<p>The token\'s value makes no sense to you, <em>but,</em> should the need arise, "appropriate means exist" by which your website can "[authoritatively] ask someone who knows (LDAP... etc.)" about any <em>and every(!)</em> question that you may have. In other words, you do <strong>not</strong> avail yourself of <em>any</em> "home-grown logic." Instead, you inquire of The Authority and implicitly trust its verdict.</p>\n\n<p>Uh huh ... it\'s <em>quite</em> a mental-switch from the "wild-and-wooly Internet."</p>\n'}, {'answer_id': 31486842, 'author': 'Iain Duncan', 'author_id': 1108964, 'author_profile': 'https://Stackoverflow.com/users/1108964', 'pm_score': 5, 'selected': False, 'text': "<p>I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&amp;auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to. </p>\n"}, {'answer_id': 32038011, 'author': 'user9869932', 'author_id': 1183098, 'author_profile': 'https://Stackoverflow.com/users/1183098', 'pm_score': 4, 'selected': False, 'text': '<p>I dont\'t know whether it was best to answer this as an answer or as a comment. I opted for the first option.</p>\n\n<p>Regarding the poing <strong>PART IV: Forgotten Password Functionality</strong> in the first answer, I would make a point about Timing Attacks. </p>\n\n<p>In the <strong>Remember your password</strong> forms, an attacker could potentially check a full list of emails and detect which are registered to the system (see link below). </p>\n\n<p>Regarding the Forgotten Password Form, I would add that it is a good idea to equal times between successful and unsucessful queries with some delay function. </p>\n\n<p><a href="https://crypto.stanford.edu/~dabo/papers/webtiming.pdf">https://crypto.stanford.edu/~dabo/papers/webtiming.pdf</a></p>\n'}, {'answer_id': 38874818, 'author': 'jwilleke', 'author_id': 88122, 'author_profile': 'https://Stackoverflow.com/users/88122', 'pm_score': 3, 'selected': False, 'text': '<p>Use <a href="http://openid.net/connect/" rel="noreferrer">OpenID Connect</a> or <a href="https://kantarainitiative.org/confluence/display/uma/Home" rel="noreferrer">User-Managed Access</a>.</p>\n\n<p>As nothing is more efficient than not doing it at all.</p>\n'}]
['https://Stackoverflow.com/questions/549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136/']