简体   繁体   中英

How to authenticate an AJAX request to a PHP file?

On my website I have a registration page which makes an AJAX request to check if a username is available after it has been entered. This file is called check.php and is in the same directory as the registration.php file. When data is posted to check.php it will perform a query at a MySQL database and return how many users it found with that username.

If anybody were to post data to the check.php file they would see the result, too. I need to stop this somehow, I've read on a few answers I need to "authenticate" each request. This is probably a very large topic although I'm not too sure what to search for to find more about it. Is authenticating each request a good way to stop unnecessary username checks? If so I would really appreciate it if anyone could point me in the right direction as to how to do this.

A solution is to generate a unique token in session, and put it in all pages that will contain a form. Post this token on each AJAX request you make. It is called CSRF protection, Cross-Site Request Forgery .

You can add a protection layer checking the user referer in HTTP headers.

Answer for common case: no - you can't prevent this, since AJAX is just an HTTP-request. It can be sent no matter how you'll protect your server. So if the point is - to protect from 'evil hackers' - there's no way to do this. The correct though is to check/validate anything on server side.

But is it's about only basic check, you can read

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')

-but be aware - this is also a data, which came from client ie it can't be trusted (actually, it's just HTTP-request header, nothing more)

我认为你可以在用户登录你的应用程序时创建一个Session变量,并检查这个变量是否具有正确的值,当你向'check.php'文件发帖时检查你的用户是否是以前的身份验证

Missing a lot of info but conceptually I am not sure you are worrying about a real risk. Bottom line is that people can use your form to check if emails exist so it's logical they can use check.php as well. Would be overkill to try and prevent that.

I have one think - you can generate some unique token, store it on SESSION before show the page. Than on each checking you must to add this token to request. check.php must regenerate token and return it new.

But each request can emulate and it not protect you from people, which want to know results of check.php. Nothing protect...

Also you can make mechanism for analyzing ip request for checking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM