I have recently started to code heavily AJAX supported scripts in PHP, thing is, the files being accessed by the AJAX calls can be directly used too, how to disable that?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Carriage Return (ASCII chr 13) is missing from tex
- PHP Recursively File Folder Scan Sorted by Modific
- How to fix IE ClearType + jQuery opacity problem i
As other people have suggested in their replies, this is not possible. This is because of one of the pillar principles of computer security: you can never trust the client. This is why we validate all input from the client, etc.
Instead of trying to block other clients from accessing your services, instead spend time writing defensive web services. Meaning, make sure that malicious users can't slip injections or other attacks through your business logic. Ex., make sure all e-mails are valid, people aren't buying items for negative dollars, etc.
Oh, and the fact that web services are open is a GOOD THING! You're providing a open API to your users, which is very neat! Maybe instead of trying to lock out your community you embrace it - give them some documentation on how to interface with your services and they'll make more clients. Instead of you buying the iPhone SDK and spending time learning Objective C, one of your users might.
Use Sessions in your application.
Editing:
Register your site in a session , I use UUIDs for that.
Set a cookie with the same value, which you use in the session.
Send your AJAX-request with a parameter which also includes this value.
Compare the values from the session, the cookie and the parameter.
You cannot reliably prevent this from happening. The key really is not to consider someone accessing this file directly as a security issue - plan for this being possible and you will be in a much more secure place.
Some people might recommend code that looks like this (or similar):
However, the fact of the matter is that HTTP headers can be spoofed quite easily and are not a means of securing code. In my testing on a busy site a while back i noticed that these headers are not actually that reliable anyway.
Maybe you should use some XSS-defense technique, like passing some secure key along with the ajax request. And only give the key to the javascript that makes asynchronous queries along with the loaded page.
In this case you won't have to worry about people passing requests to the files directly, only if you keep the keys secure, use POSTs to invoke actions and do sanity checks.
There's no way of directly disallowing access. Since a query can always be crafted to match any criteria you come up with.
If XmlHttpRequest is being used to query the server it adds a header which can be detected using something like: