如何在CakePHP上向Controller添加身份验证

时间:2017-03-28 20:31:18

标签: authentication cakephp naming-conventions

如何在CakePHP上为控制器安全地添加身份验证?我正在遵循BookMarker教程,并希望为登录添加相同类型的身份验证,但是在UserController上。这有点像格式化问题,但我不确定要输入什么才能显示,特别是不会破坏代码。任何答案将不胜感激!

<?php

// src/Controller/UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{
 public function articles()

{

}
public function index()
{
    $this->set('users', $this->paginate($this->Users->find('all')));    }

public function view($id)
{
    $user = $this->Users->get($id);
    $this->set(compact('user'));
}

public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'add']);
        }
        $this->Flash->error(__('Unable to add the user.'));
    }
    $this->set('user', $user);
}



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(['add', '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());
}


}

1 个答案:

答案 0 :(得分:0)

假设您正在使用cakephp3,希望这可以帮助您在UsersController中创建初始化操作,就像这样

public function initialize()
{
   parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'unauthorizedRedirect' => $this->referer() // If unauthorized, return them to page they were just on
    ]);

    // Allow the display action so our pages controller
    // continues to work.
    $this->Auth->allow(['display']);
}

在书签教程中,他们将此代码保存在appController中,并且所有控制器通常都会扩展此控制器,以便为所有控制器加载auth组件,但是您希望在UsersController中使用auth组件所以此代码将仅为UsersController

加载Auth组件