Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cors failing for subdomains

CORS not working properly for domain and subdomain. I've a single NodeJS server hosted at https://api.example.com I've two ReactJS Clients

Client 1. https://example.com

Client 2. https://subdomain.example.com

I've configured Client 1 to force www so that a single origin is used for Client 1. When I open Clien1 that works fine. When I open Client2 I get the error that

Access to XMLHttpRequest at 'https://api.example.com/someAPI' from origin 'https://subdomain.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://www.example.com' that is not equal to the supplied origin

When I press Ctrl+F5 then it works fine but after that If I refresh Client1 then the error comes at Client1

Access to XMLHttpRequest at 'https://api.example.com/someAPI' from origin 'https://www.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://subdomain.example.com' that is not equal to the supplied origin.

Now When I press Ctrl+F5 at Client1 then it works fine but the same error goes to the Client2.

My nodeJS server is configured as follows

var whitelist = ['https://www.example.com', 'https://subdomain.example.com'];
    getCorsCoptions(req, callback) {
    var getOriginValue = () => {
      if (whitelist.indexOf(req.header('origin')) !== -1) {
        return true;
      } else {
        log.error(__filename, 'Not allowed by CORS', origin);
        return false;
      }
    }
    var corsOptions = {
      origin: getOriginValue(),
      methods: ['GET', 'POST'],
      credentials: true,
      preflightContinue: false,,
      allowedHeaders:["Content-Type","X-Requested-With","X-HTTP-Method-Override","Accept"]
    }
    callback(null, corsOptions)
  }

app.use('*', cors(this.getCorsCoptions));
app.options('*', cors(this.getCorsCoptions));

I'm using axios at React Client sides as follows

get(url: string) {
    return Axios.get(url, {
      withCredentials: true
    }).then((res: any) => {
      if (res) {
        return res.data;
      }
      return {};
    });
}

post(url: string, data: any) {
    let requestHeaders = { 'Content-Type': 'application/json' };
    return Axios.post(url, data, {
      headers: requestHeaders
      , withCredentials: true
    }).then((res: any) => {
      if (res) {
        return res.data;
      }
      return {};
    });
}
like image 386
Inaam ur Rehman Avatar asked Apr 17 '19 13:04

Inaam ur Rehman


1 Answers

I found a solution to this problem. The browser was caching origin. Solved this problem by adding the following header in response

Cache-Control: no-store,no-cache,must-revalidate

I've also added Vary: Origin but i think it didn't solve the problem I've managed cors as follows

var whitelist = ['https://www.example.com', 'https://subdomain.example.com'];
router.all("*", (req, res, next) => {
    var origin = req.headers.origin;
    if (whitelist.indexOf(origin) != -1) {
      res.header("Access-Control-Allow-Origin", origin);
    }
    res.header("Access-Control-Allow-Headers", ["Content-Type","X-Requested-With","X-HTTP-Method-Override","Accept"]);
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods", "GET,POST");
    res.header("Cache-Control", "no-store,no-cache,must-revalidate");
    res.header("Vary", "Origin");
    if (req.method === "OPTIONS") {
    res.status(200).send("");
      return;
    }
    next();
});

where router is express.Router()

I hope that someone find this helpful.

like image 137
Inaam ur Rehman Avatar answered Oct 26 '22 01:10

Inaam ur Rehman