Skip to content


CakePHP Auth Component For Dummies Tutorial

First off, I would like to say much thanks to Gwoo for finally helping me to understand this thing.

So I know what you’re thinking; I’m probably the last person to finally figure out the CakePHP’s Auth Component. For the past few months, I’ve been using obAuth because that’s the only authentication I could get to work with CakePHP. I think that I was just making it more difficult than it should have been.

My main resource for learning the Auth Component has been Chris’s tutorial, but even then I still needed help. Also, I’m the type that doesn’t really learn much without code.

Note that I’m running off of the CaekPHP 1.2 beta.

Getting Started

Now you can modify this however you like, but I’m starting out with the basics. You’re going to need the following:

  • A user database with fields username, password. Of course they don’t need to be named that way, but defaults are fun.
  • A User Model with Controller and Views – This can be baked from CakePHP
  • A login view for the user.
  • And a base app_controller.php. That’s it.

The Setup – app_controller and users_controller

So here’s the minimum in app_controller:

var $components = array('Auth');

function beforeFilter(){
	$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display', 'home');
	$this->Auth->allow('display');
	$this->Auth->authorize = 'controller';
}
function isAuthorized() {
	return true;
}

You can always visit the API for a better understanding of what’s going on, but right now we’re just trying to get stuff working.

After that there’s the users_controller.php. This you can get straight out of CakePHP’s baking. You do need a small modification:

function login()
{
}

function logout(){
	$this->Session->setFlash('Logout');
	$this->redirect($this->Auth->logout());
}

Brief Explanation

Honestly, it’s magic; automagic to be precise. If you want to know how it works, you can read up in the API. But what I will do, is give you some of the magic words.

$this->Auth->authorize = ‘controller’

There are different types of authorization action (ugh – ACL stuff), CRUD (basically locks up all the editing stuff), and controller (gives you some need control). Hey, sorry I don’t know too much of what it does, just what I need.

$this->Auth->loginAction = array(‘controller’ => ‘users’, ‘action’ => ‘login’)

This tells yo what the login page is. It also controls where the user is redirected to if he’s not authorized to view a page.

$this->Auth->loginRedirect = array(‘controller’ => ‘pages’, ‘display’ => ‘home’)

Self explanatory: default action to redirect the user to when logged in if they go straight to the login page. If, however, they tried to access a restricted page then this will be ignored and when they login they’ll be redirected to where they wanted to go to.

$this->Auth->allow(array(‘display’))

This is one of the magic functions. By default, adding the authentication component locks down all actions, except the login and logout. This is your way of telling the component let me in to the ‘display’ action for every controller. You at least want to see the homepage right?

You can also add to this in the beforeFilter() of each controller you you need (don’t forget the parent::beforeFilter() to make sure the Auth stuff is still called). Likewise there’s a $this->Auth->deny(), which does the reverse. One small tip: you can also use allow(array(‘*’)) to allow everything.

User Controller

For right now, the login() action can be left as is. The Auth Component handles all that foot work beautifully. You just need to make sure you call $this->Auth->logout() in your logout() action. It has the added benefit of returning the Auth’s logoutRedirect, so $this->redirect($this->Auth->logout() works great.

There you have it, I hope that helps. Now if you’re still having a hard time, I got a present for you:

Download: CakePHP Auth 1  CakePHP Auth 1 (4.3 KiB, 11,471 hits)

There you’ll find some code, to get you up and running. It’s slightly different from what I got above (some extra stuff), but it’s heavily documented.

Enjoy and Happy Baking!

Posted in CakePHP.

Tagged with , , , .

Related Posts


40 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Manuel says

    $this->Auth->loginRedirect = array(‘controller’ => ‘pages’, ‘display’ => ‘home’);

    or

    $this->Auth->loginRedirect = array(‘controller’ => ‘pages’, ‘action’ => ‘home’);

    ?

  2. Baz L says

    Excellent catch Manuel…I was shooting for this:
    $this->Auth->loginRedirect = array(‘controller’ => ‘pages’, ‘action’ => ‘display’, ‘home’);

  3. ambiguator says

    just want to point out some more automagic that’s going on here when createing users (admin_add in this case)

    AuthComponent uses its own hashPassword function to encode your passwords everytime you post a data['User']['password'] field. Thus you don’t have to do any manipulation with the controller or model – thanks, AuthComponent!

    However, if you have a “confirm password” field for adding users. You’ll need to handle such a scenario manually. Since AuthComponent’s hashPassword method only takes care of data['User']['password'], i use Auth’s password method before comparing the password and the confirm password.

    this is not the optimal solution. I would like to see AuthComponent be a little automagical about hashing passwords to include confirm_password, and possibly all fields matching something like /.*passw.*/

  4. Baz L says

    Yeah, it’s a slight inconvenience. What I’ve done is something like this:

    function _saveUser()
    {
      //  Needed to call validates() before save()
      $this->User->set($this->data);
    
      //  Validate first since saved password will be hashed. If not, all other validation will pass.
      if ($this->User->validates())
      {
        if (!empty($this->data['User']['new_password']))
          $this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password'] );
    
        //  Already validated
        if ($this->User->save($this->data, false))
          return true;
      }
      else
        return false;
    }
    

  5. jerry says

    Hi, thanks for the up to date tutorial.

    I was wondering, what is the advantage of writing your own component instead of just using obAuth or othAuth?

  6. Jamessh says

    Hello,

    what if i want to allow action to GROUP of user just like how i used to in obAuth???

    Thanx

  7. Jamessh says

    Got it, the answer is on tutorial part2…

  8. The Perkster says

    Thank you! Thank you! Thank you! I was missing a couple of pieces and you had them!

  9. alex says

    You’re my hero. The tutorial, along with the source code you gave, helped me immensely understand auth and cake better. You saved me countless hours of frustration. Thank you!!!

  10. Mike Floering says

    1.

    2.
    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home2/zendscom/public_html/cake/cake/libs/controller/component.php on line 58
    3.

    4.
    Warning: Invalid argument supplied for foreach() in /home2/zendscom/public_html/cake/cake/libs/controller/component.php on line 85
    5.
    CakePHP Rapid Development
    6.
    Missing Model
    7.

    8.
    No class found for the Login model
    9.

    10.
    Notice: If you want to customize this error message, create app/views/errors/missing_model.thtml.
    11.

    12.
    Fatal: Create the class below in file : app/models/login.php
    13.

    14.

    19.

    I get that error when I install the exact files from the tutorial…and my database is set up right. That error occurs when i try to access /users/. Can anybody help? Thanks. (I’m pretty new :) )

1 2 3

Continuing the Discussion

  1. links for 2008-01-10 « Richard@Home linked to this post on January 9, 2008

    [...] CakePHP Authentication Component – Tutorial One | Web Development 2.0: Web Design, CakePHP, Javascri… (tags: cakephp authentication acl tutorial) [...]

  2. CakePHP Auth Component - Tutorial Two | Web Development 2.0: Web Design, CakePHP, Javascript linked to this post on January 11, 2008

    [...] is the second installment of my Auth Component Tutorial. I included a link to download a file for during the first [...]

  3. CakePHP Tutorials :: PseudoCoder.com linked to this post on February 10, 2008

    [...] – Simple User Registration in CakePHP 1.2 http://www.webdevelopment2.com – CakePHP Auth Component For Dummies Tutorial http://www.webdevelopment2.com – CakePHP Auth Component – Tutorial [...]

  4. CakePHP Auth Component - Tutorial Three: Remember Me Cookie | Web Development 2.0: Web Design, CakePHP, Javascript linked to this post on April 9, 2008

    [...] is the third installment of my Auth Component Tutorial. This tutorial builds on the first installment, so make sure you grab the download [...]

  5. Cake php auth tutorial for dummies | Unconventional Lippolis linked to this post on July 10, 2009

    [...] php auth tutorial for dummies http://www.webdevelopment2.com/cakephp-auth-component-tutorial-1/ Tags auth, cakephp, tutorial Categories [...]

  6. CakePHP and the (in)famous Auth component « Westsworld linked to this post on February 24, 2010

    [...] are explained here A Hopefully Useful Tutorial For Using CakePHP’s Auth Component and CakePHP Auth Component For Dummies Tutorial (so no need to go through it here as [...]



Some HTML is OK

or, reply to this post via trackback.

CommentLuv Enabled