Can I set a dynamic cors policy which only allows specific origins to pass cookies (Node.js)?

拜拜、爱过 提交于 2020-03-05 04:44:26

问题


Context

I have an express server with two types of clients.

  1. My app (React + graphql): I've enabled credentials for this client: app.use(cors({ credentials: true, origin: "http://localhost:3000" })); I've set this so that I can receive auth-related cookies from my gql client.

  2. Third-party services (via http client I provide). These requests can come from any number of origins.

I can't use the wildcard operator for the orgin (cors({origin: *})) as this would allow any site to use my users' auth cookies. However, if I don't pass the wildcard operator, third-party clients can't make requests.

I've tried unsuccessfully to enable the wildcard on a specific route.

Question

Can I set different cors policies for different origins?


回答1:


You have a couple options.

  1. You can set up a dynamic cors handler that will allow allow origins without using *.
  2. You can get whatever is needed out of the cookie and pass it some other way (as a query parameter, for example).

You can write a programmatically controlled cors handler that can allow one domain, some domains, all domains, however you write the code.

Here's one that allows all domains without using *:

var corsOptions = {
  origin: function (origin, callback) {
    console.log(`Origin ${origin} is being granted CORS access`);
    callback(null, true)
  }
}

app.use(cors(corsOptions));

You don't have to apply this globally either. You can apply it only to certain routes or only to certain routers.

Examples here: https://www.npmjs.com/package/cors in the CORS module documentation.



来源:https://stackoverflow.com/questions/60087583/can-i-set-a-dynamic-cors-policy-which-only-allows-specific-origins-to-pass-cooki

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!