Introduction
Most applications have an authentication process, which gives a user authorization to use an application. Most commonly user credentials are stored in a database table or third party APIs are used such as Facebook to authenticate users. In this article, I explain how IMAP authentication can be used to give users access to your application.
If you are developing an application where user identity information is not necessary and you have email accounts on an IMAP server, then you can use the login credentials for the email accounts to authenticate your users.
Consider the following scenario, you maintain a company application. When a new employee joins the company, they are given an email account by the network administrator. Your application can authenticate the employee using the employees email account, which means your application doesn't need to create login accounts. When an employee leaves the company, the network administrator disables their email account, which will in turn deny the employee access to your application. With this approach, all user accounts as centralized. One of the disadvantages is that, no identity information for the user apart from the email address exists. In order for your application to be selective about which users can access your application, you will need a separate lookup data store such as a database or an XML data file. This approach will mainly suit applications where identity information is not required and anyone with an email account can access the application, such as a company message board where the email address can be used to identity the employee.
The code presented below uses the IMAP protocol and its LOGIN command to authenticate email accounts.
class ImapAuthentication {
protected $con;
public function __construct($host, $port){
$this->con = fsockopen($host, $port, $errno, $errstr, 30);
$this->getResponse();
}
public function authenticate($username, $password){
fwrite($this->con, 'A1 LOGIN ' . $username . ' ' . $password . PHP_EOL);
return $this->getResponse();
}
protected function getResponse(){
while(true){
$line = fgets($this->con);
$segments = explode(' ', $line);
if($segments[1] =='OK'){
return true;
}elseif($segments[1] =='NO'){
return false;
}
}
}
}
Using the Code
$imapAuth = new ImapAuthentication('ssl://imap.gmail.com', 993);
$auth = $imapAuth->authenticate('username', 'password');
if($auth){
echo 'Login Success';
}else{
echo 'Login failed';
}
Note: For SSL connections, you must have the php_openssl
extension enabled.
This brings me to the end of this article. Please feel free to leave your comments and suggestions.
History
- 27th May, 2014: Initial version