【问题标题】:can not set cakephp AuthComponent sessionKey无法设置 cakephp AuthComponent sessionKey
【发布时间】:2014-06-11 13:04:00
【问题描述】:

我正在使用 cakephp 2.4.7 进行开发,我正在使用 auth 组件进行多次登录(用户和公司登录)。

我的目标是在beforeFilter 中设置正确的sessionKey(Auth.User 或Auth.Company)。 Auth.User 是 cakephp 中的默认值。

应用控制器:

public $helpers = array('Cache','Html','Session','Form');

public $components = array(
    'Security',
    'Cookie',
    'RequestHandler',
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array(
            'controller' => 'users',
            'action' => 'index'
        ),
        'logoutRedirect' => array(
            'controller' => 'users',
            'action' => 'login'
        ),
        'authError' => 'You must be loggedin to view this page.',
        'loginError' => 'Invalid user credentials.',
        'authorize' => array('Controller')
    )
);

public function beforeFilter() {

    $this->Auth->deny('*'); 
}

公司控制器:

public function beforeFilter() {
    parent::beforeFilter();
    AuthComponent::$sessionKey = 'Company';
    //$this->Auth->sessionKey = 'Auth.Company';
    $this->Auth->authenticate = array(
        'Form' => array(
            'userModel' => 'Company', // set the new userModel
            'fields' => array('username' => 'email')
        )
    );
    $this->Auth->allow('register', 'login', 'logout');
}

登录完美,但身份验证会话仍然是Auth.User。 (用debug($this->Auth->User());测试)

我做错了什么?如何正确设置AuthComponent::$sessionKey

【问题讨论】:

  • 您确定$this->Auth->user() 不是从会话中的Company 键读取吗?如果您尝试调试整个$this->Session->read() 或仅调试$this->Session->read('Company),会发生什么?抱歉,如果这是一个愚蠢的问题,但我认为您可以尝试一下。
  • $this->Auth->user() 返回指定会话密钥下设置的数组。因此,您真的无法检查该方法以了解信息存储在哪个会话密钥下。您的 Company 模型是否与 User 模型有 belongsTo 或 hasOne 关联?
  • 不,公司与用户模型没有关联。
  • debug(CakeSession::read('Auth')); 返回公司数组。
  • @q0re 您是使用两个不同的表来验证用户身份还是只使用一个表?如果是这样,成功登录后如何将它们重定向到相应的仪表板?请帮忙,因为我是 cakephp 新手。

标签: php cakephp authentication cakephp-2.4


【解决方案1】:

我今天遇到了同样的问题,我已经跳入代码(here) 来检查它为什么不适合我。

看来你得这样设置

public function beforeFilter()
{

    AuthComponent::$sessionKey = 'Auth.Company'; // static property so we have to 
    // access in static way so you want get strict errors
    ...
}

然后注销并再次登录用户。在您的操作中,只需 var_dump()pr() $this->Session->read('Auth')

顺便说一句 $this->Auth->user() 将始终返回您在 Auth 中的数组,由 [$sessionKey] 和 AuthComponent::user() 静态调用相同。

【讨论】:

  • 对于 cakephp 3.0,我们可以在 AppController.php 中使用 public function beforeFilter(Event $event) { $this->Auth->sessionKey ='Auth.Company; } 为前端和后端设置不同的 sessionKey。
  • 听起来不错,但这个问题是关于 cakephp 2.4.7 的。
  • 哦!我刚刚为需要蛋糕 3 版本的人添加了。如果不相关,我应该删除我的评论吗?
  • 由你决定,但我认为你可以留下它,也许它会对某人有用。
猜你喜欢
  • 1970-01-01
  • 2014-02-07
  • 2012-07-15
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多