Tutorial :How can I use cookies for authentication in CakePHP?



Question:

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 generated by auth.example.com (using a Perl CGI program).

To login in to needpassword.example.com, I need to redirect to auth.example.com to set the cookie, and then use CakePHP to parse the cookie.

How do I parse this cookie? And how do I modify the Auth component to do these?

And how can I override the Auth class to instead go to the auth.example.com to authenticate, and not using the User model? By overriding the identify method in Auth.php?

Many thanks.


Solution:1

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.


Solution:2

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)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »