Is there any easy way to configure CakePHP auth component to send out a json response instead of normal redirect to login url.
Im using many ajax requests, and when the session expires, the ajax request will get a response of my home page's html instead of json encoded status.
I would like CakePHP to send out the following json response, if user is not logged in, and the query was made using json extension.
{status: false, message: "Please log in"}
Non-ajax page loads would still need to redirect as usual.
You should look upon where is the system checking whether you are logged in and see the case where it is not logged in. Wrap the following if
around it:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//put here the html for the log in screen
} else {
$response = '{status: false, message: "Please log in"}';
echo json_encode($response);
}
Since it is hard to determine if you are making an ajax request, Cake 3 uses X-Requested-With = XMLHttpRequest. It seems this is a default for jquery (but who uses that anymore? seriously.).
You will need to set that header manually to allow cakephp to detect that your request is indeed ajax.
Your ajax requests may work on other pages because you are probably setting the _serialize var and setting the Accept Header or using the .json extensions to force json. However, the auth function does not check the Accept Header it only checks the X-Requested-With header.
So verify in your xhr request that X-Requested-With is XMLHttpRequest and you should receive a 403.
If you want to further customize the element or data that is returned, checkout the AuthComponent ajaxLogin param.
Basically, you will need to set the value to an element you want rendered. Cake will look in your Element Template path and load that element.
// In your AppController
$this->loadComponent('Auth', [
'ajaxLogin' => 'yourAjaxElement', // This is what is important
// Optional stuff....
'authenticate' => [
'Form' => [
'finder' => 'AuthUser'
]
],
'authorize' => ['Controller'],
// More settings...
Then create this element
Template/Element/yourAjaxElement.ctp
Happy coding.