2

I have a public Single Page Application (SPA) that is calling my backend REST service via JavaScript. How can I secure the REST service so that it will only accept calls from my SPA and no other clients or users? Basically, my SPA should be the only allowed user of the service.

Any way that I can think to secure it would involving storing some kind of secret, however because the SPA is written completely in JavaScript anyone can view the source.

kimsagro
  • 121
  • 2
  • I'd write this in answer with some more explanation, but I wouldn't feel good about it since it's not really an answer. To sum it up for you: You're trying to achieve the impossible. With our current technology (and, frankly, any relevant technology I can imagine), there's no way to do what you're trying to do. The closest thing is restricting your SPA to authenticated users and then generate a short-lived secret for each user that is sent to the browser after login. – Adi Mar 22 '14 at 14:12

3 Answers3

4

You can't, really. Anything sent via javascript can be tampered with. Because of this your SPA will be vulnerable to XSS and MITM attacks. An option would be using session tokens and obfuscation which is such a grotesque solution. Plus this will be an opening for CSRF attacks: CSRF. Otherwise, I recommend having your users login so that there will be some form of authentication.

dperconti
  • 241
  • 1
  • 6
0

You can configure CORS(Cross origin Resource Sharing) to respond to requests coming from a particular domain. In node JS there is a package to do it.

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://linktoyourSPA.com',
}

app.use(cors(corsOption));

This would allow requests only from that particular domain.

If you are not using nodeJs. You can manually set response header Access-Control-Allow-Origin.for more info read this https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Balaji S
  • 1
  • 2
  • "no other clients" sounds to me like he wants to prevent _all_ other clients, not just javascript coming from other domains. CORS does nothing to prevent trivial crafting of requests with curl or other software. – AndrolGenhald Jul 07 '18 at 16:25
0

I guess its not 100% possible. As per my understanding, what you can give try is using cryptographic nonce. Learn more about nonce at - http://en.wikipedia.org/wiki/Cryptographic_nonce

The simple way I would try to achieve this. 1. Generate an initial nonce. 2. Use this nonce in next communication with the server. 3. At server, verify that the nonce is generated by my application only 4. Create a new nonce and piggy-back it along with the response. 5. Go to step 2 and use the new nonce.