Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Login Authentication in cakephp 3.0

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.73k
    Comment on it


    Hello Reader's ,
    Hope your are doing good today.

    Today we will discuss about login Authentication in cakephp 3 using Auth Component.Authentication is a very important part of any application.
    If you are working on user based project then you need to authenticate user before login.

    First Let’s create a table in blog database to hold our users’ data:

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

    Step 2: Create model class UsersTable.php
    Location : src/Model/Table/UsersTable.php

    namespace App\Model\Table;
    use Cake\ORM\Table;
    use Cake\Validation\Validator;
    
    class UsersTable extends Table
    {
    
        // Validate field befor login
        public function validationDefault(Validator $validator)
        {
            return $validator
                ->notEmpty('username', 'A username is required')
                ->notEmpty('password', 'A password is required')                     
        }
    
    }

    Step 3: Now load Auth Component in your AppController.
    Location : src/Controller/AppController.php

    namespace App\Controller;
    
    use Cake\Controller\Controller;
    use Cake\Event\Event;
    
    class AppController extends Controller
    {
    
        public function initialize()
        {
            $this->loadComponent('Flash');
            $this->loadComponent('Auth', [
                'loginRedirect' => [
                    'controller' => 'Articles', // type your own Controller
                    'action' => 'index'
                ],
                'logoutRedirect' => [
                    'controller' => 'Users',
                    'action' => 'index',
                ]
            ]);
        }
    }
    
    
    //What we did in the beforeFilter() function was to tell the AuthComponent to not require a login for all index() and view() actions, in every controller. We want our visitors to be able to read and list the entries without registering in the site.
    
    public function beforeFilter(Event $event)
        {
            $this->Auth->allow(['index','view']);
        }

    step 4: Now authenticate user.

    Location: src/Controller/UsersController.php

    namespace App\Controller;
    use App\Controller\AppController;
    use Cake\Event\Event;
    
    class UsersController extends AppController
    {
        // Other methods..
    
        public function beforeFilter(Event $event)
        {
            parent::beforeFilter($event);
            // Allow users to register and logout.
            // You should not add the "login" action to allow list. Doing so would
            // cause problems with normal functioning of AuthComponent.
            $this->Auth->allow(['logout']);
        }
    
        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());
        }
    }


    step 5: Now Create login page.

    Location: src/Template/Users/index.ctp

    
    //src/Template/Users/index.ctp
    
    <div class="users form">
    <?= $this->Flash->render('auth') ?>
    <?= $this->Form->create() ?>
        <fieldset>
            <legend><?= __('Please enter your username and password') ?></legend>
            <?= $this->Form->input('username') ?>
            <?= $this->Form->input('password') ?>
        </fieldset>
    <?= $this->Form->button(__('Login')); ?>
    <?= $this->Form->end() ?>
    </div>

    I hope this will help you.Please feel free to give us your feedback in comments.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: