No system is foolproof. Point! What you can do is add sequential layers of protection.
- Check how the request was made
You yourself have already researched and found how to do it, but the way you did it is not exactly the most appropriate, programmatically speaking, because you delete an error instead of dealing with it.
Also, you assume a marry specific for comparison which is not certain in view of the existence of several frameworks JS which, assuming they send this header automatically, can suddenly capitalize some letters differently, for example.
That said:
function isXmlHttpRequest() {
$header = ( array_key_exists( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ?
$_SERVER['HTTP_X_REQUESTED_WITH'] : '' );
return ( strcmp( $header, 'xmlhttprequest' ) == 0 );
}
if( ! isXmlHttpRequest() ) {
// Acesso negado
}
Lately here at Sopt much has been said about controlling the origins of an XHR. AJAX is not crossdomain, but can become because of a poorly configured server. Better to prevent than remedy:
header("Access-Control-Allow-Origin: http://www.domain.com");
The most recommended way is to attach to the request URL some random value that you, and only you have to validate.
This can be from an MD5 hash to a uniqid() stored in session despite what if you are EVEN interested in violating your Sesssions application can be captured. I don’t go into detail because I don’t know exactly how it’s done.
Or else token "for real", which may even come from the same uniqid() but encrypted with a rough algorithm (things from RIJNDAEL 256 bits or more), stored in a database associated with the user ID, short duration, being constantly regenerated.
SSL should come first, but be it for purchasing availability or deployment complexity, I left it last. ;)
What is the language you have on the server side?
– Sergio
in case it would only refuse external requests... da to do this with the server firewall, or not?
– RodrigoBorth
@Sergio php and nodejs.
– Filipe Moraes
@Filipe apache or Nginx server?
– RodrigoBorth
@Rodrigoborth got the apache.
– Filipe Moraes