Most of the times when you want to create an application in CakePHP you can just create the database and then bake it. Its ready with all CRUD functionalities. But if you need to add authentication in the application you need to do it manually. Just follow the tutorial and you are ready with User Authentication in CakePHP

Step 1 – Create users table in your databases using following SQL Code

CREATE TABLE users (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(255),
created DATETIME DEFAULT NULL
);

Step 2 – Add Auth Component in your AppController.php to enable Authentication. Your AppController.php should look like:

<?php
/**
 * Authentication in CakePHP grasphub.com by Usman Ghani
 */

App::uses('Controller', 'Controller');


class AppController extends Controller {
	public $components = array(
		'Paginator',
        'Flash',
        'Session',
        'Auth' => array(
            'loginRedirect' => array(
                'controller' => 'users',
                'action' => 'index'
            ),
            'logoutRedirect' => array(
                'controller' => 'users',
                'action' => 'login',
            ),
            'authenticate' => array(
                'Form' => array(
                    'passwordHasher' => 'Blowfish',                    
                )
            )
        )       
    );
}

Step 2 – Update your User Model at app/Model/User.php

We used username & password fields because CakePHP can handle login functionality easily with these names. Use the following code in your User.php:

<?php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

/**
 * User Model
 */
class User extends AppModel {

	public function beforeSave($options = array()) {
	    if (isset($this->data[$this->alias]['password'])) {
	        $passwordHasher = new BlowfishPasswordHasher();
	        $this->data[$this->alias]['password'] = $passwordHasher->hash(
	            $this->data[$this->alias]['password']
	        );
	    }
	    return true;
	}

}
?>

We are using Blowfish Password Hasher for hashing our passwords.

Step 3 – Update your UsersController.php as instructed below:

Add following at top of Controller to enable password hashing at adding user.

App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

And add login, add & logout functions in your UsersController.php

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }        
    }
    
    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Flash->success(__('Logged in successfully.'));                
                return $this->redirect($this->Auth->redirectUrl());
                
            }
            $this->Flash->error(__('Invalid username or password, try again'));            
        }
    }

    public function logout() {		
	return $this->redirect($this->Auth->logout());
    }

As we have used beforeSave function in our User Model so every time we add the user the password will be automatically hashed using Blowfish. So don’t worry about hashing manually.

Now whenever you open your application it will redirect you to login page. So to stop the redirect from Users Add form just add the following code in your UsersController.php:

public function beforeFilter() {
	parent::beforeFilter();		
	$this->Auth->allow('add');
}

It will help disabling Auth controller on add form so that users can register to your application then can login using credentials they have used.

Hope it helps you in integrating Authentication in CakePHP Application.

The code is tested with CakePHP version 2.7.

Feel free to comment for any problem or suggestions.

Thanks and Happy Coding.

User Authentication in CakePHP 2.7http://www.grasphub.com/wp-content/uploads/2015/10/cakephp2-1024-768-1024x768.jpghttp://www.grasphub.com/wp-content/uploads/2015/10/cakephp2-1024-768-150x150.jpg UG ArticlesCakePHPProgramming,,
Most of the times when you want to create an application in CakePHP you can just create the database and then bake it. Its ready with all CRUD functionalities. But if you need to add authentication in the application you need to do it manually. Just follow the tutorial...
Most of the times when you want to create an application in CakePHP you can just create the database and then bake it. Its ready with all CRUD functionalities. But if you need to add authentication in the application you need to do it manually. Just follow the tutorial and you are ready with User Authentication in CakePHP <strong>Step 1 - Create users table in your databases using following SQL Code</strong><code> </code> <pre class="lang:mysql decode:true ">CREATE TABLE users ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), password VARCHAR(255), created DATETIME DEFAULT NULL );</pre> <strong>Step 2 - Add Auth Component in your AppController.php to enable Authentication. Your AppController.php should look like:</strong> <pre class="lang:php decode:true "><?php /** * Authentication in CakePHP grasphub.com by Usman Ghani */ App::uses('Controller', 'Controller'); class AppController extends Controller { public $components = array( 'Paginator', 'Flash', 'Session', 'Auth' => array( 'loginRedirect' => array( 'controller' => 'users', 'action' => 'index' ), 'logoutRedirect' => array( 'controller' => 'users', 'action' => 'login', ), 'authenticate' => array( 'Form' => array( 'passwordHasher' => 'Blowfish', ) ) ) ); }</pre> <strong>Step 2 - Update your User Model at app/Model/User.php</strong> We used username & password fields because CakePHP can handle login functionality easily with these names. Use the following code in your User.php: <pre class="lang:php decode:true"><?php App::uses('AppModel', 'Model'); App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth'); /** * User Model */ class User extends AppModel { public function beforeSave($options = array()) { if (isset($this->data[$this->alias]['password'])) { $passwordHasher = new BlowfishPasswordHasher(); $this->data[$this->alias]['password'] = $passwordHasher->hash( $this->data[$this->alias]['password'] ); } return true; } } ?> </pre> We are using Blowfish Password Hasher for hashing our passwords. <strong>Step 3 - Update your UsersController.php as instructed below:</strong> Add following at top of Controller to enable password hashing at adding user. <pre class="lang:php decode:true">App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');</pre> And add login, add & logout functions in your UsersController.php <pre class="lang:php decode:true">    public function add() {         if ($this->request->is('post')) {             $this->User->create();             if ($this->User->save($this->request->data)) {                                  return $this->redirect(array('action' => 'index'));             } else {                 $this->Flash->error(__('The user could not be saved. Please, try again.'));             }         }             }      public function login() {         if ($this->request->is('post')) {             if ($this->Auth->login()) {                 $this->Flash->success(__('Logged in successfully.'));                                 return $this->redirect($this->Auth->redirectUrl());                              }             $this->Flash->error(__('Invalid username or password, try again'));                     }     } public function logout() { return $this->redirect($this->Auth->logout()); }</pre> As we have used <strong>beforeSave</strong> function in our User Model so every time we add the user the password will be automatically hashed using Blowfish. So don't worry about hashing manually. Now whenever you open your application it will redirect you to login page. So to stop the redirect from Users Add form just add the following code in your UsersController.php: <pre class="lang:php decode:true ">public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow('add'); } </pre> It will help disabling Auth controller on add form so that users can register to your application then can login using credentials they have used. Hope it helps you in integrating Authentication in CakePHP Application. The code is tested with CakePHP version 2.7. Feel free to comment for any problem or suggestions. Thanks and Happy Coding.