Let's say I have some code that creates an HTML page with a JSON service call.
How can I prevent others from copying and pasting the source code, calling the service and getting the result set for the first user?
If I get the domain as a parameter for the service or get something else like username or password, they could also be copied and pasted and used for another domain.
I don't see a way of preventing this or am I wrong?
You are correct that there is no way to absolutely prevent this, but you can make it a lot more difficult and you can make it so that you can identify the user who is either abusing the API or was hacked themselves.
The way to do this is by using certificates (asymmetric encryption). Each client has a private and a public key, that are completely unique to that client. The public key is public knowledge (typically stored on the server or in a third party database like Comodo or Verisign). The private key is private to the client. The server also has a private/public key.
Each time the client makes a request, the request is encrypted with the server's public key, and signed (encrypted) with the client's private key. The server's key ensures that only the server can decrypt the request, and the client's key ensures that only the client could have encrypted that request such that it is perfectly reversible using the client's public key.
This means that a malicious user will only be able to make requests under his/her own name, so you will know who is messing around, or you know which user was compromised so you can inform him/her and disable their account. This also prevents other users from sniffing on the wire and recovering another user's request to perform a replay attack.
There are other ways to implement this, such as using secure cookies to track the user requests. I'll post some links to helpful questions regarding secure cookie implementations for you. Some of these are for other platforms but the concepts are the same.
This is a lot to take in. You'll probably want to do some more reading before beginning your implementation.
Other helpful questions:
- REST Web Service authentication token implementation
- Security When Using REST API in an iPhone Application
https://stackoverflow.com/questions/15390354/api-key-alternative/15390892#15390892 Link Broken.