Cakephp 3认证教程loginredirect问题

时间:2015-12-29 11:52:52

标签: php authentication cakephp

我已经按照官方网站上的教程进行了操作,但重定向部分第一次无法正常工作

  

第1步:转到用户/登录并使用正确的凭据登录   结果:登录成功但重定向到pages / home而不是文章/索引   第2步:再次转到用户/登录并使用正确的凭据登录   结果:正确重定向到文章/索引(会话已登录)

我该如何解决这个问题?

在我尝试授权部分之前似乎工作正常。(不确定)。但我已经评论了所有授权部分。仍然没有修复。

我缺少什么?

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', [
        //  'authorize' => ['Controller'], // Added this line
            'loginRedirect' => [
                'controller' => 'Articles',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    //public function isAuthorized($user)
    //{
    //    // Site Admin can access every action
    //    if (isset($user['role']) && $user['role'] === 'admin') {
    //        return true;
    //    }
    //
    //    // Default deny
    //       return false;
    //
    //}

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

}
?>

更新

如果我直接访问登录URL,即用户/登录然后登录,它就能完美运行。 但是我的页面/主页中有一个按钮,可以在点击时重定向到用户/登录页面。 通过按钮使用此路线,如果我登录,我将面临问题。

注意:如果使用debugKit查看会话信息,则显示重定向到/

home.ctp文件中的按钮代码

<?php echo $this->Html->link('<span class = "glyphicon glyphicon-log-in"></span> Login',['controller' => 'users', 'action' => 'login'],['escape' => false]);?>

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

通过编写此代码来解决此问题:

UsersController:

if($this->Auth->Login()){
    $this->redirect($this->Auth->redirect());
}

AppController的:

public function beforeFilter(){
    if($this->here != '/cmap/users/login'){
        $this->Session->write('Auth.redirect', $this->here);
    } 
}

此处,$this->here是您的文件路径。希望这对你有所帮助!

答案 1 :(得分:0)

从CakePHP文档,关于$ loginRedirect: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent :: $ loginRedirect

  

如果用户在其会话中具有Auth.redirect值,则将忽略此值。

所以你的$this->Auth->loginRedirect被忽略了。您可以手动从会话中删除Auth.redirect值。这是一个快速入侵,无需更改每个URL的值。

$session = $this->request->session();
if($session->read('Auth.redirect') === '/') {
    $session->delete('Auth.redirect');
}
相关问题