lenniekid
lenniekid

Reputation: 891

Angular interceptors and CORS

I am trying to write an interceptor to add a token to all HTTP requests using Angular. I am using roughly the recipe given here - https://thinkster.io/interceptors

So the code uses http module factory and a tokenInterceptor() function. I can successfully add a token as a header to the request - but now when it passes through the interceptor, it gets blocked by some kind of CORS blocking mechanism. I get this error in chrome console -

XMLHttpRequest cannot load http://127.0.0.1:/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:/' is therefore not allowed access. The response had HTTP status code 403.

I tried setting the access control allow origin header like below in my interceptor to no avail:

config.headers['Access-Control-Allow-Origin'] = '*';

I have tried some suggestions online but none helped. Does anything at all need to be done on client side to fix CORS related issues - or is it all a server side concern?

Upvotes: 8

Views: 18524

Answers (3)

Gustavo Daniel
Gustavo Daniel

Reputation: 2478

I had exactly the same issue: receiving CORS error only when adding a token header with an interceptor:

req = req.clone({
  setHeaders: {
    "x-auth-token": session ? session.token : ''
  }
});

In my Node.js api server I had the following middleware:

  app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

The problem were occurring because the 'x-auth-token' header was not in the list of allowed headers, so I added it:

  app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, x-auth-token'); // HERE
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

This solved the problem instantly.

Upvotes: 1

adrisons
adrisons

Reputation: 3723

The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors.

This makes your app more secure.

CORS gives web servers the ability to say they want to opt into allowing cross-origin access to their resources.

Instead of using CORS, I recommend you use a proxy in your angular server, so:

  • in the browser, the real resource wont be displayed (more privacy and security)
  • your code is more isolated from the specific source

Implementation

Create a proxy.conf.json in your app

{

    "/client-api/*": {
      "target": "http://127.0.0.1",
      "pathRewrite": { "^/client-api": "" },
      "secure": false,
      "logLevel": "debug",
      "changeOrigin": true
    }
  }

In your angular.json file, under projects.<your-project-name>.architect.serve.options add

"proxyConfig": "src/proxy.conf.json"

Where you make the http request, just use the url origin client-api.

For example, to get the list of countries, you request client-api/countries, and the proxy will transform it to http://127.0.0.1/countries

Upvotes: 2

sideshowbarker
sideshowbarker

Reputation: 88146

The server that’s responding to the request needs to send the Access-Control-Allow-Origin response header for OPTIONS requests, not just for GET and POST requests.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Response to preflight request doesn't pass access control check

The reason the browser gives you that error is: before it attempts the actual request you’re trying to make from your frontend JS code, the browser sends an OPTIONS request to see if the server responds in a way indicating it’s opting in to receiving requests of the kind you’re trying to make.

So your server-side code needs to add handling for the OPTIONS request to respond with Access-Control-Allow-Origin, Access-Control-Allow-Headers & Access-Control-Allow-Methods.

Does anything at all need to be done on client side to fix CORS related issues - or is it all a server side concern?

There’s nothing you can do on the client side to change the behavior or to get your browser to not emit that error. CORS config is all a server-side concern. Your server must handle the OPTIONS.

The response had HTTP status code 403.

That indicates an authorization failure. That could be just because your server isn’t configured to ever send a success response (200 or 204) for OPTIONS requests—in which case you must configure to to do that (to send a 200 or 204 with the right Access-Control-Allow-* headers and no response body)—or it could be because you’re trying to send a request that requires authorization and the authorization is failing.

Upvotes: 6

Related Questions