Marco C
Marco C

Reputation: 111

CakePHP 3 allow only REST index.json and and.json (no normal views) with Auth

I've created the blog from blog tutorial, and I would to protect articles list, but I want that this be accesible across REST, I've activated json extensions.

All works well. I can add and retrieve list, but now I want to deny index and add from web and only be accesible from .json to public.

I tried with

    public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->Auth->allow('index.json');
}

But this obviously doesn't work. All webpage is login protected as is in tutorial. Web services should be accesible to Android App (code is ready and working).

Thank you!

Upvotes: 1

Views: 911

Answers (1)

ndm
ndm

Reputation: 60463

Of course that doesn't work, the allow() methods expects valid method names, and that's all the authentication component cares about, method/action names, it doesn't matter how the action was requested.

What you are trying to do requires you to check the type of the request, and based on the results, allow the actions. Checking the request type can be done using Request::is().

See Cookbook > Request & Response Objects > Checking Request Conditions

So it might be as simple as

if ($this->request->is('json')) {
    $this->Auth->allow(['index', 'add']);
}

Upvotes: 3

Related Questions