There is no absolutely reliable way to prevent this, as any header information can be tampered with. Another possible solution is session-based tokens, but in this case your javascript is publicly available, so anyone who wants to spend a little time can determine how your token system works and find out how to do it.
The combination of methods will give you the broadest protection. You can search for a header, use a .htaccess file, and use tokens. This approach, based on all of the above conditions, makes it much harder to use for a web server - most of the abuse comes from people trying to find an easy hole to use. It is important to remember that you cannot calm down because you have deployed the βbestβ defense or because you have so many levels of protection that it seems impossible to crack. If someone really wanted him to be bad enough and have time, they will find a way. These types of preventative measures are actually only deterrents to avoid the lazy, curious and lazy spiteful. Targeted attacks are a whole separate security class and, as a rule, are more focused on server-level security issues.
Htaccess example. This is not something you would put in your root, but rather in a subfolder where you have scripts that should never be called from the address bar:
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?_YOUR_DOMAIN_NAME_HERE.com [NC] RewriteRule \.(php)$ - [NC,F,L]
Check out this article for information on using the token system: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
source share