【问题标题】:How can I use cookies for authentication in CakePHP?如何在 CakePHP 中使用 cookie 进行身份验证?
【发布时间】:2009-07-17 04:18:24
【问题描述】:

我正在尝试使用我域中其他页面设置的 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 中的 identify 方法?

非常感谢。

【问题讨论】:

  • 您是否检查过使用绝对 URL(即auth.example.com)设置 AuthComponent::loginAction 参数是否有效?

标签: cakephp cookies authentication


【解决方案1】:

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

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

这将允许您完全重写组件,但缺点是您在升级 cake 时将不再收到对 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()) { ... }

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

【讨论】:

    【解决方案2】:

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

        $auth = $_COOKIE['auth'];

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

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

    (注意:time() + 300 将 cookie 的过期日期设置为未来 5 分钟,您可能需要更改此设置)

    【讨论】:

    • 嗨,它看起来很简单,这正是我想要的。那么如何覆盖 Auth 类,转而去 auth.example.com 进行身份验证,而不是使用 User 模型?
    • 最好使用控制器中的 CookieComponent 或自定义 AuthComponent 而不是 PHP 的 setcookie() 方法。
    猜你喜欢
    • 2014-06-06
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 2019-02-08
    相关资源
    最近更新 更多