Cakephp 3 Login functionality-Authentication and Authorization – Part 1

Spread the love

In this post, I am going to share a procedure of creating Cakephp 3 Login functionality in our Cakephp 3 application. The Authentication or Login/Logout system is very common and basic requirement of any web application.

So let’s see what would be the steps included while implementing Authentication and Authorization or Cakephp 3 Login functionality.

Authentication means identifying whether the user which is going to use your application, is a valid user or not and Authorization means checking whether that user is having permissions to access certain functionalities of your application. In part 2 we will see the implementation of authorization functionality.

So first let’s create a table which stores the user’s information in your Cakephp 3 application.

Steps required to create Cakephp 3 Login functionality:

Step 1: Create a “users” table.

Create a users table in your database with following basic fields:

1. id
2. name
3. username
4. password

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100),
    password VARCHAR(255),
    
);

Step 2: Bake the users table using cake bake functionality of Cakephp 3.

The baking process will create UsersTable.php, User.php, all the basic ctp files and UsersController.php in your application. Please check for the baking process in Cakephp3. We will see all the above mentioned files going forward.


Step 3:

While implementing Cakephp 3 Login functionality, we have to use built in component named “Auth”. In AppController load “Auth” component in “initialize” method, using “$this->loadComponent(‘Auth’);”.

<?php
namespace AppController;

use CakeControllerController;
use CakeEventEvent;

class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        
        $this->loadComponent('Auth');
    }

}
?>

Refresh the page of your application in the browser.
What happened?
You will get an error – “Missing Method in UsersController”. Here it will show that “login” method is missing in “UsersController”. So first lets add login method.

You will also require “logout” method, so lets create logout method also.

<?php

namespace AppController;

use AppControllerAppController;

class UsersController extends AppController {

    public function login() {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

    public function logout() {
        return $this->redirect($this->Auth->logout());
    }
    //Below are basic crud methods of UsersController
}
?>

As you see in login method,
=> “$user = $this->Auth->identify();” this line identifies the logged in user is valid or not and stores the user object in “$user” variable.
=> “$this->Auth->setUser($user);” this line will set the logged in valid user in Auth component for using all over the application.
=> “$this->Auth->redirectUrl()” is the url where the user should redirect after login. Its not default. We have to “redirectUrl” in AppController, in Auth component settings. Which we will see soon.

Similarly in, logout method,

=> “$this->Auth->logout()” will redirect user after logout from application. Same will be in Auth component settings.

Add below setting in Auth component in AppController.

<?php

namespace AppController;

use CakeControllerController;
use CakeEventEvent;

class AppController extends Controller {

    public function initialize() {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Posts',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

}

?>

In above Auth component settings, “loginRedirect” and “logoutRedirect” are having those controllers and actions, where the user should get redirected after login and logout respectively. Lets proceed to next step of implementing Cakephp 3 Login functionality.


Step 4:

Refresh the page. Again you will get an error message “Missing Template”, indicating “login.ctp” is missing in “<path>srcTemplateUsers” location. So lets create a login.ctp and add a login form in the login.ctp file.

<!-- File: src/Template/Users/login.ctp -->

<div>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->control('username') ?>
        <?= $this->Form->control('password') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>

Save and refresh, you will see the simple login page with username and password fields. Currently, this form will not work, as we have not yet added a user in the users table.


Step 5:

Add user using “add” method of your UsersController. Open add page in your browsers. In this case, I am using “http://localhost/blog/users/add”. If you hit add method in URL you will again redirect back to login page. This happens because now Auth component is not allowing any action to be accessible without a login.

So in order to allow add a method to be accessible without login, we have to tell our “UsersController” to allow this method. This is possible by adding “beforeFilter” methods in “UsersController” and using “$this->Auth->allow(‘add’);” in “beforeFilter” method. Like below.

<?php

namespace AppController;

use AppControllerAppController;
use CakeEventEvent;

class UsersController extends AppController {

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow('add');
    }
    
    public function login() {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

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

    public function add() {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }

        $this->set(compact('user'));
        $this->set('_serialize', ['user']);
    }
 
 //...
   
}

Step 6:

Refresh page. This will show add page with “FirstName”, “Username” and “Password” fields. But wait. Don’t add a user right now. However, if you add a user it will save successfully in users table but the password will be pain text and not an encrypted one. We have to make sure the passwords saved in the application should be in encrypted form while implementing CakePHP 3 Login functionality.

To encrypt the password while adding a user, we have to use “DefaultPasswordHasher” class in User.php, which is an entity class, for the password field. So open a User.php entity class and add “_setPassword” function. “_setPassword” function automatically set the encrypted password in the users table.

// src/Model/Entity/User.php
namespace AppModelEntity;

use CakeAuthDefaultPasswordHasher;
use CakeORMEntity;

class User extends Entity
{

    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

    protected function _setPassword($password)
    {
        if (strlen($password) > O) {
            return (new DefaultPasswordHasher)->hash($password);
        }
    }

}

Refresh the page and add a user with username and password and check that password saved in encrypted format in users table.


Step 7:

You will see after adding a user page will redirects to the login page again. Now login in the application with your username and password and check the redirection.

It might get redirected to users index page as because of previous add method redirection which is “index” method.

Logout using “http://localhost/blog/users/logout”. The page will redirect to the login page again. But as we have set the “logoutRedirect” to “Pages” controller and “display” method, flow should be redirected to home page. This is not happening because we have to allow “display” method in either “AppController” or “UsersController”. So add a “beforeFilter” with “allow” in AppContoller as below.

// src/Controller/AppController.php

namespace AppController;

use CakeControllerController;
use CakeEventEvent;

class AppController extends Controller
{
    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Posts',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    public function beforeFilter(Event $event)
    {
        $this->Auth->allow(['display']);
    }
    
}

Login again. Now the flow should redirect to posts index method and after logout, redirection should be on the homepage.

That’s it. In this first part, we have covered an Authentication functionality. In the second part, we will see how to implement Authorization of the users in details.

Hope you will get a clear picture of authentication of users and login functionality in this tutorial.

Subscribe here by email for more tutorials:

http://www.submissionwebdirectory.com/computers_and_internet/


Spread the love

2 thoughts on “Cakephp 3 Login functionality-Authentication and Authorization – Part 1”

Leave a Comment