如何在CakePHP中使用cookie进行身份验证?

时间:2009-07-17 04:18:25

标签: cakephp cookies authentication

我正在尝试使用我域中其他页面设置的Cookie来验证用户身份。 假设我使用cakephp编写了needpassword.example.com, 并且cookie由auth.example.com生成(使用Perl CGI程序)。

要登录needpassword.example.com,我需要重定向到auth.example.com来设置cookie,然后使用CakePHP来解析cookie。

如何解析此Cookie?如何修改Auth组件来执行这些操作?

我如何覆盖Auth类来转而使用auth.example.com进行身份验证,而不是使用User模型?通过覆盖Auth.php中的识别方法?

非常感谢。

2 个答案:

答案 0 :(得分:2)

由于您的需求听起来超出了AuthComponent最初设计的设计,因此您有两种选择。

首先,如果它确实不符合您的需求,您可以创建和维护您自己的AuthComponent。通过将/cake/libs/controller/components/auth.php复制到/app/controller/components/auth.php来完成此操作。

这将允许您完全重写组件,但缺点是当您升级蛋糕时,您将不再接收AuthComponent的更新。

其次,您可以使用以下模式扩展CakePHP中的任何内容:

// save as: /app/controllers/components/app_auth.php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
    function identify($user = null, $conditions = null) {
        // do stuff
        return parent::indentify($user, $conditions);
    }
}

..并使用AuthComponent替换控制器中AppAuthComponent的所有实例。

  • 您只需要定义要替换的方法。
  • 您可以在方法期间的任何时候使用parent::...
  • 运行原始AuthComponent中的方法(甚至是已重新定义的方法)
  • 方法参数应保持in the same order as the original API以保持一致。
  • 如果您想添加更多方法参数,请将它们放在API之后,例如:

    function identify($user = null, $conditions = null, $custom = array()) { ... }

此方法允许您在必要时仍使用核心中定义的最新方法进行特定于应用程序的自定义。

答案 1 :(得分:0)

假设我理解您的问题...只要auth.example.com使用域“.example.com”设置cookie,用户浏览器就会将请求与needpassword.example.com一起发送给您能够使用以下内容在PHP脚本中访问它:

    $auth = $_COOKIE['auth'];

然后,您可以使用以下内容更改Cookie:

    setcookie( "auth", "value", time() + 300, "/", ".example.com" );

(注意:time()+ 300将cookies到期日设置为未来5分钟,您可能想要更改此内容)

相关问题