问题
Context
I have an express server with two types of clients.
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.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.
- You can set up a dynamic cors handler that will allow allow origins without using *.
- 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