1

I have a nodejs / express application that server some html pages as well as a rest service. Those html pages call the rest service via XMLHttpRequest. The rest service can also be called by external application.

On server side, in my rest service, I want to check if the request comes from the same domain or not because I want external application only to authenticate their request (e.g. providing an access token).

To do so, I look at req.headers.referer to get the url of the page originating the request and compare with my server domain. Is is safe? Can req.headers.referer be altered by an external app trying to call my service without authentication?

Is there a smarter / safer way to do so?

lviggiani
  • 5,824
  • 12
  • 56
  • 89

2 Answers2

2

According to this answer: https://stackoverflow.com/a/29531709/3953525 headers can be manipulated. And as in the answer, I'd recommend to use an authentication token instead of trusting headers.

Enric A.
  • 893
  • 10
  • 18
1

You should have some sort of authentication even if you are calling it from the same origin as origin can be easily manipulated/faked.

If you are rendering HTML on the server side then only sending that rendered HTML to the client then you can use origin as it will be localhost always but the best way to do this will be a use some sort of templating engine like jade or EJS and render HTML on server side else use react/angular on frontend side and manage the things from the client side rather than using ajax for critical requests.

Ridham Tarpara
  • 5,970
  • 4
  • 19
  • 39