I'm trying to use AJAX to autocomplete a search box on my website. I was using firebug to test my application. When I try to search something, Firebug tells me that the AJAX request returned a 403 forbidden error. However, when I copy the EXACT URL that was in the AJAX request, it returns the correct data.
Edit: I think this has to be something on the JavaScript side. Are there any headers that might be omitted with an AJAX request compared to a normal request?
Here is the $_SERVER variable (I removed the parameters that were the same on both requests) on an AJAX request that failed (1) vs typing the URL in and it works (2):
(1)
2011-04-02 13:43:07 Debug: Array
(
[HTTP_ACCEPT] => */*
[HTTP_COOKIE] => CAKEPHP=0f9d8dc4cd49e5ca0f1a25dbd6635bac;
[HTTP_X_REQUESTED_WITH] => XMLHttpRequest
[REDIRECT_REDIRECT_UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REDIRECT_UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REMOTE_PORT] => 60252
[UNIQUE_ID] => TZdgK654EmIAAEjknsMAAAFG
[REQUEST_TIME] => 1301766187
)
(2)
2011-04-02 13:44:02 Debug: Array
(
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[HTTP_COOKIE] => CAKEPHP=d8b392a5c3ee8dd948cee656240fd5ea;
[REDIRECT_REDIRECT_UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REDIRECT_UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REMOTE_PORT] => 60281
[UNIQUE_ID] => TZdgYq54EmIAAF7zt6wAAAJJ
[REQUEST_TIME] => 1301766242
)
If you are using Auth, you need to make sure that you are logged in if the controller/action is not on your
$this->Auth->allow()
list.Make sure you set debug to 0 as well, might cause you some problems.
Maybe it's the Cross site request forgery component. It's responsible for all authentication requests, except GET requests. Look at this: http://book.cakephp.org/3.0/en/controllers/components/csrf.html
I think I found the solution. I set the security level to medium to solve the issue. I found this line in the config folder. Does a medium security level pose any problems in production?
Edit: This is definitely the solution. Here's what was happening:
When the security level is set to high, a new session ID is generated upon every request.
That means that when I was making ajax requests, a new session ID would be generated.
If you stay on the same page, JavaScript makes a request, which generates a new session_id, and doesn't record the new session_id.
All subsequent ajax requests use an old session_id, which is declared invalid, and returns an empty session.