Etsur

We use interaction design & strategy to build awesome websites.



PHP Authentication of ExpressionEngine Users

In a recent project we were working on, we had the need for an external application to verify an account's credentials stored in an ExpressionEngine database. 

Normally, when approaching this type of problem we would take the username and password of the authenticating user, hash the password, and compare it against the database. Due to the sparse documentation on how the ExpressionEngine password hashing functionality works, and becuase the possible methods used to hash a password can vary (md5 or sha1, salt or no salt, etc.) between different member accounts (for example, after running a member import), we felt it wise not to manually hash the passwords.

Thankfully, after a bit of research, we found a way to hook into ExpressionEngine's built in authentiation function. This function automaticaly handles all the hashing and database comparisons for us —  all we need to do it provide it with a username and unhashed password. At its most basic, the function looks as follows:

$this->EE->auth->authenticate_username($username, $password);

As you can see, you just pass a plaintext username and password and the function will handle the rest — ouputting "true" if the credentials are correct, otherwise "false".

 Now, we'll show you an example of this function being used as part of an ExpressionEngine plugin. If you need some background on how to create a simple ExpressionEngine plugin, check out the official documentation.

public function authenticate_app_user()
{
	$this->EE->load->library('auth');	//Load authentication library
	$authorized = false;
	$username = $this->EE->input->post('username');
	$password = $this->EE->input->post('password');
	if (!empty($username) && !empty($password))
	{
		$authorized = $this->EE->auth->authenticate_username($username, $password);
		if ($authorized)
		{
			//Do whatever you want to now that the user is authorized
		}
	}
	return $authorized;
}

It's that easy!