Whats the Best Way to Do User Authentication in PHP

Whats the best way to do user authentication in php?

use Sessions. Store the session id in the cookie, and store the state of the user on the server side (loggedIn, userId, IP).

To clarify what you need to store in the session array:

  • loggedIn: A boolean variable about whether the user is logged in or not. You reuse the same cookie for multiple sessions, so you remember the users username next time they come to your site, etc.
  • userId: The uniqe id of the user in the database. Use this to get more information on the user, like username, email etc. This too can be kept in the session array after the user logs out.
  • IP: To prevent someone from stealing the session id and using it, you store the IP of the user as well. This is optional, as sometimes you want to allow the user to roam (eg, stackoverflow allows me to move about with my laptop without logging me out when the IP changes).
  • lastPing: The timestamp the user was last seen. This can be used instead of the cookie expiration date. If you also store the lifetime of the session, then you can log the user out due to inactivity. This means that the session id cookie can be stored on the users computer for a very long time.

When the user logs out or is logged out due to inactivity, you simply set loggedIn to false. When the user logs in with the right username and password you set loggedIn to true and update the other fields (userId, IP, lifetime). When the user loads a page, you check the lastPing against the current time and the lifetime, and either update lastPing or logout the user.

The session data can either be stored in the filesystem or in a database. If stored in a database, then userId is either a foreign key to the user record, or all the data can be put in the user record.

Hashing

rehashing a value several times is not a good idea, because you reduce the security. Instead use salt, combining a static salt (name of the page for example) and the username of the user, together with the password. A hash that takes a long time isn't better than a fast hash, a hash that results in a large digest is better than a hash that results in a short digest (due to brute force). Using SHA1 should be good enough for a normal site (IE, not a bank or a secret military organization).

What should I use for user authentication in PHP?

Check this answer here.

Although the answer is 3 years old, the suggested phpass library is up to date.

Also, +1 to Aron Cederholm. Password security is an extensive subject and you should look first at the related questions already discussed here on StackOverflow so you will be more familiar with the subject and best practices in security.

Although I like frameworks (Symfony, Zend, etc) as they generally implement these good practices, just using them don't make you a good programmer. You have to learn its inner workings. I always salute a programmer dwelving into coding his own secure authentication mechanism (as long as they don't implement it in a live site that really needs strong security), because that's the best way to learn and understand the inners of the subject. Always start from an existing implementation, and THEN use that as an example for creating your own codebase.

What is the best way to create a PHP login page?

As has been said, there's quite a lot to creating a robust and secure authentication system in PHP, but the fundamentals are easy to grasp.

The first thing you want to do is call session_start(). Once you've done this you can get and set session variables using the $_SESSION superglobal:

session_start();
$_SESSION['foo'] = $foo;
$bar = $_SESSION['bar'];

Once you've done this you can set log in details for the current user upon a successful log in and have them persist over pages (remembering to call session_start before using them). Also, session_start must be called before any content is sent to the browser.

There are security issues to consider, such as session fixation and cookie theft, however. One approach to session fixation, for example, is to regenerate the user's session ID upon elevation of privileges using PHP's session_regenerate_id (or something like that).

The PHP Security Consortium has lots of useful info.

Cookies can be manipulated using the setcookie function.

PHP best practices for user authentication and password security

OpenID 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 here.

PHP best practice on user authentication for a website?

Your SQL statement has an injection vulnerability in it. (This is under the assumption that the "submitted" suffix means the variable hasn't had any filtering done on it.) If a malicious user were to submit 'admin@example.com' AND 1=1;-- as an email address, they could log in with the credentials of "admin@example.com", irrespective of the password. I'd suggest to secure the input to the SQL and/or use stored procedures. I'd also suggest loading only the columns that you absolutely need; it will improve the speed of the query and allow less state to be held in suspension outside of the database.

Additionally, implement salting on the password. If someone were to retrieve the user's data from the database, the passwords would be an easy target for bruteforce and dictionary attacks (like rainbow tables). If you're really paranoid, consider switching from MD5 to SHA or another hashing function.

Make sure of which variables are set in your php.ini file and that they are set to values you expect. Depending on those settings, the array assignment to $_SESSION is also insecure. Some old web applications utilized a PHP 'feature' which made variables in the query string become global variables in the web application, which meant that when it executed $_SESSION['userid'] = $userid;, if a malicious user attached ?userid=1 to their query string, they would become the user with the user ID of 1, which often was the first user (or administrator).

Single User Authentication with PHP

For each page that needs authentication, you could use the session to see if the user was authenticated or not, and if not, redirect him to the authentication page.

For example, if you had an admin.php page that needed authentication, you could begin with:

<?php

session_start();

if (empty($_SESSION['authenticated'])) {
header('Location: authenticate.php');
exit;
}

/* rest of the script ... */

Then, authenticate.php can be a simple script that asks for the password. If the password is correct (if ($_POST['password'] == "secret")), it simply sets $_SESSION['authenticated'] = true.

php sessions to authenticate user on login form

what about using this to setup session

session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}

and at the top of each "secure" page use this code:

session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}

this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:

session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");

How to best store user information and user login and password

Don't store passwords. If it's ever sitting on a disk, it can be stolen. Instead, store password hashes. Use the right hashing algorithm, like bcrypt (which includes a salt).

EDIT: The OP has responded that he understands the above issue.

There's no need to store the password in a physically different table from the login. If one database table is compromised, it's not a large leap to access another table in that same database.

If you're sufficiently concerned about security and security-in-depth, you might consider storing the user credentials in a completely separate data store from your domain data. One approach, commonly done, is to store credentials in an LDAP directory server. This might also help with any single-sign-on work you do later.

What is the best way to securely authenticate a user ? (session, cookies, php, mysql)

The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for $logged.

It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User id or some other unique information in the Cookie as well.

You may also want to keep a timestamp of when the $logged was put in the DB, so that you can run cleaning queries where they are older than x days/weeks.



Related Topics



Leave a reply



Submit