PHP best practices for user authentication and password security

PhpAuthentication

Php Problem Overview


What are the best current libraries/methods to authenticate users without the use of a CMS or heavy framework?

Responses should include suggestions for anything you think should be considered the standard for new PHP development involving user authentication.

Php Solutions


Solution 1 - Php

http://openid.net/">OpenID</a> is a method to authenticate users based on their existing accounts on common web services such as Yahoo, Google and Flickr.

Logins to your site are based on a successful login to the remote site.

You do not need to store sensitive user information or use SSL to secure user logins.

A current PHP version of the library can be found http://www.openidenabled.com/php-openid/">here</a>;.

Solution 2 - Php

Implementing user authentication securely without relying on a framework (or third-party library, such as OpenID) to do it for you is not a trivial undertaking.

At a 10,000 foot overview, you have to decide:

  • Do you have usernames, email addresses, or user IDs as a primary selector?
  • How should you store passwords? PROTIP: password_hash() or scrypt are the way to go.
  • How should you handle "remember me" checkboxes? There are a lot of bad strategies for this on the Internet. Treat every one of them with skepticism, because they might introduce vulnerabilities into your application.
  • How should the application handle users who forget their password?

The information in this answer is relevant and up-to-date as of May 9, 2015 and might be obsoleted by the conclusion of the password hashing competition

Primary Selectors

In general, usernames and email addresses are better than ID numbers.

There should be no security requirement to keep usernames secret, because in practice they will be leaked when someone tries to register anyway.

You can decide whether or not to treat email addresses as a secret. Users generally like not being exposed to spammers, scammers, and trolls.

Password Hashing

You should use password_hash() and password_verify() unless you are sufficiently experienced with writing cryptography libraries to go above and beyond.

Beyond Bcrypt

Sometimes developers like to get creative (e.g. adding a "pepper", which usually means pre-hashing or HMACing passwords with a static key) and go beyond the standard implementations. We ourselves have done this, but very conservatively.

For our internal projects (which have a much higher margin of security than most people's blogs), we wrote a wrapper around this API called PasswordLock that first hashes a password with sha256, then base64 encodes the raw hash output, then passes this base64-encoded hash to password_hash(), and finally encrypts the bcrypt hash with a properly-implemented encryption library.

To reiterate, instead of peppering, we encrypt our password hashes. This gives us more agility in case of a leak (we can decrypt then re-encrypt because we know the key). Additionally, we can run our webserver and database on separate hardware in the same datacenter to mitigate the impact of a SQL injection vulnerability. (In order to start cracking hashes, you need the AES key. You can't get it from the database, even if you escape to the filesystem.)

// Storage:
$stored = \ParagonIE\PasswordLock\PasswordLock::hashAndEncrypt($password, $aesKey);

// Verification:
if (\ParagonIE\PasswordLock\PasswordLock::decryptAndVerify($password, $stored, $aesKey)) {
    // Authenticated!
}
Password Storage with PasswordLock:
  1. hash('sha256', $password, true);
  2. base64_encode($step1);
  3. password_hash($step2, PASSWORD_DEFAULT);
  4. Crypto::encrypt($step3, $secretKey);
Password Verification with PasswordLock:
  1. Crypto::decrypt($ciphertext, $secretKey);
  2. hash('sha256', $password, true);
  3. base64_encode($step2);
  4. password_verify($step3, $step1);

Further Reading

Solution 3 - Php

I use OpenID .

But like stackoverflow I use the Google project openid-selector to do the heavy lifting.
Demo Page here.

The obvious advantages (of OpenID) are.

  • You don't need to be a security expert.
  • Users trust the big sites with their info.
  • You can request things like (nickname etc) but user has to opt in.
  • You don't need to worry about:
  • registration processes
  • lost/forgotten password

Solution 4 - Php

A lot of great answers here, but I feel like it's worth saying this--do NOT try to re-invent the wheel in this case! It is extremely easy to screw up user authentication in a wide variety of ways. Unless you really need a custom solution, and have a firm knowledge of security schemes and best practices, you will almost certainly have security flaws.

OpenID is great, or if you're going to roll your own, at least use an established library and follow the documentation!

Solution 5 - Php

http://www.openwall.com/phpass/">PHPass</a> is a lightweight, variable cost password hashing library using bcrypt.

Variable cost means that you can later turn up the 'cost' of hashing passwords to seamlessly increase security without having to invalidate your previously hashed user passwords.

The field size used for hash storage is constant even when increasing 'cost' due to increasing not the size of the hash, but the number of iterations required to produce it.

Solution 6 - Php

Login using HTTP AUTH

  1. Using Apache: http://httpd.apache.org/docs/2.2/howto/auth.html
  2. It is also possible with IIS and other web servers.

Once authenticated, for PHP, you just have to use $_SERVER['PHP_AUTH_USER'] to retrieve the username used during authentication.

This can be a faster and, sometimes, more flexible solution than handling the solution at scripting level provided that limited information is needed regarding the user as all that is made available to you is the username used to login.

However, forget about integrating your authentication in an HTML form unless you implement a full HTTP AUTH scheme from within your scripting language (as described below).

Rolling your own HTTP AUTH within your scripting language

You can actually extend HTTP Basic Auth by emulating it in your scripting language. The only requirement for this is that your scripting language must be able to send HTTP headers to the HTTP client. A detailed explaination on how to accomplish this using PHP can be found here: (see more on PHP and HTTP AUTH).

You can expand on the article above using a typical authentication schema, file store, even PHP sessions or cookies (if information isn't needed to be persistent), giving you much more flexibility when using HTTP AUTH, yet still maintaining some simplicity.

Downsides to HTTP AUTH

  1. The main downside to HTTP auth is the complications that logging out can have. The main way to clear the user's session is to close the browser, or pass off a header with 403 Authentication Required. Unfortunately, this means the HTTP AUTH popup comes back on the page and then requires users to either log back in or hit cancel. This may not work well when taking usability into consideration, but can be worked around with some interesting results (ie. using a combination of cookies and HTTP AUTH to store state).

  2. HTTP AUTH popups, session, and HTTP header handling is determined by browser implementation of the standard. This means that you will be stuck with that implementation (including any bugs) without the possibility of workaround (unlike other alternatives).

  3. Basic auth also means auth_user and password show up in server logs, and then you have to use https for everything because otherwise username and password also go over the network on every query in plain text.

Solution 7 - Php

It's important to separate the security layer of your application from the rest of it. If there's no distance between your application logic and your communication system, you are free to communicate insecurely in one place and securely somewhere else. Maybe you'll make a mistake and send a password in an unencrypted cookie, or maybe you'll forget to verify the user's credentials for one step. Without a 'right way' to communicate with the user, you're sure to make a mistake.

For example, let's say this is how you verify users now:

user_cookie = getSecureCookie()
if (user_cookie.password == session_user.password) {
do_secure_thing()
...
}
If a vulnerability is discovered in getSecureCookie(), and you use this code to verify users throughout your application, you might not find all the instances of getSecureCookie() that need to be fixed. If, however, you separate your logic from your security:
if (userVerified()) {
do_secure_thing()
...
}
... you will be able to quickly and easily re-secure your application. Give yourself a 'right way' to do security, and you will be far less likely to make a major security blunder.

Solution 8 - Php

Best authentication is to utilize multi-factor authentication, ideally a token-less version on all security sensitive log-ons.

Password protected and easier to use with high reliability and security. There are several available beyond EMC/RSA. I prefer SwivelSecure's PINSafe.

Igor S

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaren SchwenkeView Question on Stackoverflow
Solution 1 - PhpDaren SchwenkeView Answer on Stackoverflow
Solution 2 - PhpScott ArciszewskiView Answer on Stackoverflow
Solution 3 - PhpMartin YorkView Answer on Stackoverflow
Solution 4 - PhpDougWView Answer on Stackoverflow
Solution 5 - PhpDaren SchwenkeView Answer on Stackoverflow
Solution 6 - PhpPatrick AllaertView Answer on Stackoverflow
Solution 7 - PhpEvan KroskeView Answer on Stackoverflow
Solution 8 - PhpIgor SillView Answer on Stackoverflow