CakePHP – How to allow unauthenticated access to specific pages

I have created a CakePHP app where I have created a UsersController, which handles all about users.
When I try to browse www.mydomain.com, if I am logged in, it let’s me see the index (app/View/Pages/home.ctp). Else, it redirects me to mydomain.com/users/login and persists to log in.

I have tried looking at AppController.php, PagesController.php or app/Config/core.php and app/Config/routes.php, but did not find anything. My UsersController.php, also, is not responsible for that, I think.

I do not remember and I cannot find how to disable this. Which file should be responsible for that?

EDIT:my CakePHP version is 2.3.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Generally you can make specific actions public using the auth components allow() method.

Making pages public may require a little more work in case you’d want to make only specific pages public, since the PagesController handles all pages in a single action (display()). If that is the case, then you could utilize request->params['pass'][0] which will hold the page name, test this against a list of allowed pages, and then allow the display action using Auth::allow.

Example, in the PagesController:

public function beforeFilter()
{
    parent::beforeFilter();

    $allowedPages = array('home', 'foo', 'bar');
    if(isset($this->request->params['pass'][0]) &&
       in_array($this->request->params['pass'][0], $allowedPages))
    {
        $this->Auth->allow('display');
    }
}

This would allow the pages home, foo and bar to be viewed without being logged in.

If you’d wanted to make all pages public, then you could simply use Auth::allow without any conditions, ie:

public function beforeFilter()
{
    parent::beforeFilter();
    $this->Auth->allow('display');
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply