Reputation: 85
I need to filter json requests and allow basic authentication for those requests, while allowing only form authentication for html requests. When I filter the requests in my initialize function in AppController.php:
if ($this->request->is('json')) {
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Basic' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'contain' => ['Districts']
]
]
]);
} else {
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'contain' => ['Districts']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
The json request creates and stores a session allowing the user to then access the rest of the site, including html requests because it has an authorized session. I struggled trying to find what was causing this and eventually found that you have to explicitly declare that the storage medium for the Basic Authentication method as 'Memory'. I'll post the correct code in my answer below.
This question is similar to this one for cakephp 2: CakePHP form authentication for normal requests with basic authentication for JSON
Upvotes: 0
Views: 502
Reputation: 85
You have to explicitly declare that the Basic Authentication uses Memory for the storage medium, or else it will create a session. Here is the correct code:
if ($this->request->is('json')) {
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Basic' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'contain' => ['Districts']
]
],
'storage' => 'Memory'
]);
} else {
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'contain' => ['Districts']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
Upvotes: 2