Reputation: 13361
In my CMS, I have a page which loads lots of mini-interfaces into a panel using AJAX. Those interfaces come from various PHP files in a /ajax
directory.
Would it be possible somehow to only allow access to those files using ajax, and not just by browsing to them?
My concern is, of course, that someone finds out about the /ajax
directory, and gets access to the core functionality of the CMS without even having to login. Of course I could import my user class and authenticate each of the AJAX files individually, but would it be possible to only allow access through AJAX?
Upvotes: 1
Views: 4257
Reputation: 9217
Well, an alternative option you could have is to use post
method to get the content from the php, and in your php you should set a key for the post
method. And then system wide remove cross origin access. :)
Upvotes: -1
Reputation: 39389
Authenticate your AJAX files. If there are lots of them, create a class and extend it in each individual AJAX file.
/ajax/abstract.php
:
<?php
abstract class AjaxHandler {
public function __construct() {
// import authentication handler
if ($authenticated) {
$this->display();
}
else {
header('HTTP/1.1 401 Unauthorized');
exit;
}
}
}
Then in each file, i.e. /ajax/get_user_profile.php
:
<?php
class GetUserProfile extends AjaxHandler {
public function display() {
// do your routine
}
}
Upvotes: 0
Reputation: 10074
AJAX is almost same request as Standart request you can check header but this is not secure way. So short you can't do this. Authetificate on server side what you have proposed.
Upvotes: 1
Reputation: 943100
Would it be possible somehow to only allow access to those files using ajax, and not just by browsing to them?
No.
You could add extra HTTP headers, or modify existing ones (such as Accept
) when you make the request from JavaScript … but since you are trying to do this for security reasons, that would be insufficient.
Of course I could import my user class and authenticate each of the AJAX files individually
Do that. Ajax requests are not special. They are just HTTP requests. End points created for Ajax should be secured with authentication/authorization just like any other HTTP request end point.
Upvotes: 5
Reputation: 24363
Simple answer, "no".
Your ajax files should also validate the user is logged in the same way as the front end of your system does.
Upvotes: 1
Reputation: 413682
From outside a browser, it's possible for anybody to initiate HTTP requests to any public URL on your site. There's nothing special about AJAX requests other than headers, and those can be spoofed easily.
Now what can't be easily spoofed is a secure session mechanism. If you're requiring people to log in, then you should be doing that anyway.
Upvotes: 2
Reputation: 51
No. A hacker could just fake Ajax requests, anyway. You need to authenticate everywhere or you'll get screwed.
Upvotes: 5