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, 17,717 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!

Comments

  1. Wahid Sadik says:

    Kevin, this is exactly what I needed. Thank you so much for the tutorial.

  2. $this->Auth->authorize = …; allows you to set
    function isAuthorized(){

    }
    and you can determine how the user is actually authorized instead of having the AuthComponent do it automatically by comparing the user model.
    So setting it to ‘controller’ you would define the isAuthorized() method in your controller.
    You could also set it to ‘model’ and stick the isAuthorized() method inside the model. There are also more settings such as ‘actions’ and ‘crud’ which are explained in more detail at http://book.cakephp.org/view/248/AuthComponent-Variables
    -Sam

  3. I’m interested in downloading the source files for this tutorial, but the page says that “You need to be a registered user to download this file.”, but I can’t find any way of registering.

  4. Foroct Fralion says:

    Thanks for this tutorial it has helped me to do many of the things I wanted to do with my cake project.

    I am having one problem though. I want a user to be able to log in and be redirected to their user page. Your example shows $this->Auth->loginRedirect = array(‘controller’ => ‘pages’, ‘display’ => ‘home’) and I know that by calling $auth[‘User’][‘username’] I can call up the logged in users username so I figured that I could use

    $this->Auth->loginRedirect = array(‘controller’ => ‘users’, ‘action’ => ‘view’, $auth[‘User’][‘password’] );

    but that doesn’t work. Do you have any thoughts as to how I would allow a person to log in and redirect them to a their user page (/users/view/username)?

    Thanks!

    • Foroct Fralion says:

      sorry I meant to say

      $this->Auth->loginRedirect = array(‘controller’ => ‘users’, ‘action’ => ‘view’, $auth[‘User’][‘username’] );

      Obviously passing the password field would not work

  5. Great stuff.
    Hi guys, I’m having trouble with combining my register and log in view. On the Users Controller I have two actions: registration and login and both action work different views, but when I combine the views to make it look like Facebook (i.e. the reg and login is on the same view), then it throws this error: “Error: The view for UsersController::registration() was not found.”
    Anybody help please!

  6. Could you please add this to your beforeFilter?
    if (isset($this->params[‘requested’])) {
    $this->Auth->allow($this->action);
    }

    It’s for when you get stuck in an infinite redirect loop because of an Element with an inline request on the page that renders the login form. =)

  7. Hello Kevin, how to create multi user access level with different model controller.
    It same like ACL but i not need using ACL coz ACL cache more data. I m using CakePHP 1.3.2

Trackbacks

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

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

  3. […] – 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. […] is the third installment of my Auth Component Tutorial. This tutorial builds on the first installment, so make sure you grab the download […]

  5. […] 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 […]