How can I use cookies for authentication in CakePHP?

后端 未结 2 1426
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 23:56

I am trying to use a cookie that is set by other page in my domain to authenticate the user. Say I have needpassword.example.com written using cakephp, and the cookie is gen

相关标签:
2条回答
  • 2021-01-15 00:20

    Presuming I understand your question... As long as auth.example.com sets the cookie with the domain ".example.com" the users browser will send it along with the request to needpassword.example.com and you will be able to access it in your PHP script with the following:

        $auth = $_COOKIE['auth'];

    You can then make changes to the cookie with the following:

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

    (Note: time() + 300 sets the cookies expiry date to 5 minutes in the future, you may want to change this)

    0 讨论(0)
  • 2021-01-15 00:23

    Since your needs sound outwith AuthComponent's originally intended design you have two options.

    Firstly, if it really doesn't fit your needs, you could create and maintain your very own AuthComponent. Do this by copying /cake/libs/controller/components/auth.php to /app/controller/components/auth.php.

    This would allow you to rewrite the component completely, but the downside is you will no longer receive updates to AuthComponent when you upgrade cake.

    Secondly, you can extend just about anything in CakePHP using the following pattern:

    // 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);
        }
    }
    

    .. and replace all instances of AuthComponent in your controllers with your AppAuthComponent.

    • You only need to define the methods you wish to replace.
    • You can run methods from the original AuthComponent (even ones you have redefined) at any point during your methods using parent::...
    • The method arguments should remain in the same order as the original API for consistency.
    • If you wish to add more method arguments, put them after the API ones, eg:

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

    This approach allows you to make application-specific customisation while still using the latest methods defined in the core where necessary.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题