如何防止跨域ajax请求? [英] How to prevent cross-domain ajax requests?

查看:97
本文介绍了如何防止跨域ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测我的php脚本是否正从另一个域调用,另一个域是否正在非法使用我的脚本?有办法防止这种情况吗?

How can I detect if my php script is being called from another domain and the other domain is making illegal use of my script? Is there a way to prevent this too?

UPDATE

我发现这个问题,但是它还不安全,它可以spoofed。

I found this question on SO, but its still not safe, it can be spoofed.

推荐答案

没有任何绝对万无一失的方法来防止这种情况,因为任何标题信息都可能被欺骗。基于会话的令牌是另一种可能的解决方案,但在这种情况下,您的JavaScript是可公开访问的,所以任何想花一点时间的人可以确定您的令牌系统的工作原理,并找出一个办法。

There isn't any absolutely foolproof method to prevent this, since any header information can be spoofed. Session-based tokens are another possible solution, but in that case your javascript is publicly accessible, so anyone who wanted to spend a little time could determine how your token system works and figure out a way around it.

方法的组合将给你最广泛的保护。您可以查找标题,使用和.htaccess文件,并使用令牌。这种所有的上述方法使得它更难以滥用一个Web服务器 - 大多数滥用来自人们试图找到一个容易漏洞利用。重要的是要记住,你不能自满,因为你已经部署了最好的保护,或者因为你有这么多层的保护,似乎不可能破解。如果有人真的想要它足够糟糕,有时间,他们会找到一种方法。这些类型的预防措施实际上只是阻止懒惰,好奇和空闲恶意的威慑。定向攻击是一个完全独立的安全类,通常更侧重于服务器级安全问题。

A combination of methods will give you the most wide-ranging protection. You can look for the header, use and .htaccess file, and use tokens. This sort of all-of-the-above approach makes it that much harder to abuse a web server - most abuse comes from people trying to find an easy hole to exploit. The important thing to remember is that you can't become complacent because you've deployed "the best" protection, or because you've got so many layers of protection that it seems impossible to crack. If someone really wanted it bad enough and had the time, they'll find a way. These types of preventative measures are really only deterrents to keep away the lazy, curious, and idly malicious. Targeted attacks are a whole separate class of security, and usually are more centered on server-level security issues.

样例htaccess。这不会是你放在你的根,而是在一个子文件夹中,你有不应该从地址栏中调用的脚本:

Sample htaccess. This would not be something you'd put in your root, but rather within 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]

请参阅这篇文章,了解如何使用令牌系统: https:// www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet

Check out this article for info about using a token system: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet

这篇关于如何防止跨域ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆