Reputation: 844
I've searched previous answers but can't seem to find the exact answer.
I am using ajax to call a controller action. This controller action does some other stuff then calls a public function of my user controller:
Request::factory("/user/savepoints/".$new_total);
How can i secure my action_savepoints in the User controller from people just entering it as a URL?
I currently have this at the top of my function but it doesn't do what im looking for.
if( ! $this->request->is_initial() ):
HTTP::redirect('/error');
endif;
Thanks for your help.
Upvotes: 0
Views: 215
Reputation: 1889
Either use an HTTP POST request, which can't be done just by entering a URL. (Though it can spoofed, or done via a form)
Or:
How about generating a kind of token on the server, getting it to the ajax code somehow, then passing it back in the ajax request.
Obviously they could still forge the request manually if they pull the token out of your page, but you issued them the token in the first place.
You could make the token single-use, time limited, or user-specific. Make sure it contains some kind of checksum with a server secret to prevent people building their own tokens.
Upvotes: 1
Reputation: 2882
Do you want to prevent any unauthorized users to run the script or do you want to make sure that the script only can be run via AJAX calls?
For the first, you can just check if the user is logged in. The AJAX request uses the same session as the ordinary requests.
if (Auth::instance()->logged_in())
For the second you need to check the HTTP headers if it's an AJAX call. But note that this is not a safe way to do it as HTTP headers can be altered by the client and can not be trusteed.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
//This is an ajax call
}
Unfortunately, there's no bullet proof or safe way to detect an AJAX request other than this.
Upvotes: 0