Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect PHP endpoints called by AJAX

My app consists of several PHP endpoints which are accessible via AJAX. The problem is they are also accessible via anyone who makes an HTTP request to the same endpoint. I can add checks for HTTP_X_REQUESTED_WITH and HTTP_REFERER as specified in this answer, but these can be spoofed. I could add a secret key that needs to be posted with the request, but anyone viewing the javascript and/or the console would be able to see this key. What is the solution here?

like image 414
GluePear Avatar asked Dec 24 '22 08:12

GluePear


1 Answers

People often think that because they're using Ajax requests regular sessions don't work. They do. If you have an endpoint to delete something from the database that's visible in the source code, such as:

example.com/user/1/delete

You can protect this request from non authenticated users the same way you would when using a non Ajax HTTP request in the browser. Using sessions. If the user has the privileges to remove users, this route will work, otherwise return an error (or do nothing).

You can also protect an API using OAuth. There's a great document here that explains how it works: http://tatiyants.com/using-oauth-to-protect-internal-rest-api/

like image 146
BugHunterUK Avatar answered Dec 28 '22 11:12

BugHunterUK