Reputation: 2363
I have an Angular application that connects with my server. For internal reasons I want to be able to send the origin domain to the server as it can be accessed from a couple places, for example:
https://domain1.com/app
https://domain2.com/app
In order to do that I would like my Angular app to set the Origin header. I have an interceptor and I tried to do something like this:
return next.handle(req.clone({setHeaders: {Origin: environment.origin}}));
However, it throws an error that says Refused to set unsafe header "Origin"
. I understand why, but how can I tell Angular to include this header and set it to the current domain (or just set it how it normally would)? I don't need it set to anything special, I just need it included.
Upvotes: 2
Views: 5980
Reputation: 227
We cannot set the header Origin from the Front end as its technically forbidden to do it from angular. Most browsers follow same origin policy where its not allowed to cross-communicate with different domain and these restriction is eased only if the domain is allowed access from the server.
But the CORS issue can be resolved only through server side by setting 'Access-Control-Allow-Origin' to whatever domain you want to enable the access. Some example by using Nodejs
const app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://domain1.com/app');
next();
});
Upvotes: 1
Reputation: 943100
The Origin header is sent automatically (by the browser) on cross-origin Ajax requests (and on some other cross-origin requests such as those for fonts or involving the crossorigin
attribute).
It isn't sent for same-origin requests, and you can't make it be sent because it is a Forbidden header (so websites can't lie about the Origin to bypass CORS checks).
Since it is set for cross-origin requests you can treat its absence as a signal that the request is a same origin request. Test for that instead.
Obviously, if the request does not come from a browser then it typically won't have an Origin header, but you can't depend on that for security as any non-browser source for a request could easily forge the Origin header.
Upvotes: 1
Reputation: 4617
I believe the header you should set instead is Referer
. The usage description of this header fits your scenario really well.
You could also track the access patterns on your server using a fully custom header too.
Upvotes: 1