2

I have to implement an internal API for a website which is called with jQuery ajax. It returns data on JSON.

The catch: it should only throw data when it is called from the same website. I'm assuming that an IP won't work because it is called with javascript on the client side.

For example, if someone tries to call the json url from another domain, it should throw a error message.

Any ideas?

Andres SK
  • 10,779
  • 25
  • 90
  • 152
  • 1
    Long story short: Not possible. Use proper authentication instead – Pekka Oct 31 '11 at 22:37
  • There is no authentication :( it is an open form with results. It is done via jQuery Ajax to avoid reloading the page. – Andres SK Oct 31 '11 at 22:40
  • @andufo then there is no reliable way. However, a normal JSON call won't work anyway because of the Same Origin Policy... But anybody who *wants* to access your data, will be able to. – Pekka Oct 31 '11 at 22:41
  • sorry, had not fully understood your question. My answer was stupid xD – elboletaire Oct 31 '11 at 22:44

1 Answers1

4

One way that might be enough here is to provide csrf token (secret key) from the backend when the user loads your page. Then pass that token when doing the ajax requests to make sure the user uses webpage from your servers. At least for Django there is support for csrf tokens built in, probably the same for other frameworks too.

NOTE: This does not make your data/API access more secure, but it makes it more difficult for other websites to use access to your API. This is not an alternative to proper authentication.

Links:

Community
  • 1
  • 1
Lycha
  • 9,937
  • 3
  • 38
  • 43
  • 1
    This doesn't help fully, as the attacker can just grab your page to get a CSRF token, then query away. CSRF tokens are to prevent an attack on your *user* by hijacking *his session*. They don't restrict access to the API. – derobert Oct 31 '11 at 22:45
  • 1
    @derobert Yes, but it might be enough for some usecases. As people mentioned in the comments, there is no perfect solution without authentication. At least this would prevent people from doing mashups using your api. – Lycha Oct 31 '11 at 22:49
  • 1
    It may very well be enough for some use cases, but its important that anyone reading the answer be aware of how easy it is to defeat. Its irresponsible, IMO, to give security recommendations *without* specifying its known (and substantial) weaknesses. – derobert Oct 31 '11 at 22:52
  • @derobert I didn't understand the question as asking to build security. I thought he just wanted to prevent abuse from other websites using the API. Anyway, I added a note on my answer to make it absolutely clear. – Lycha Oct 31 '11 at 23:06