koajs / cors

Cross-Origin Resource Sharing(CORS) for koa
Other
732 stars 82 forks source link

Make it possible to permit CORS requests for multiple origins #12

Closed eladnava closed 8 years ago

eladnava commented 8 years ago

Hi, Loving the package so far! Well done.

The following code can be used to specify a specific origin for CORS using kcors:

var cors = require('kcors');

// Configure cross-origin requests from localhost:3000
var config = {origin: 'http://localhost:3000'};

app.use(cors(config));

It would be great if we could specify more than one origin via an array:

var config = {origin: ['http://localhost:3000', 'http://mydomain.com']};

app.use(cors(config));

It's possible to specify multiple hosts using separate Access-Control-Allow-Origin headers, e.g:

Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Origin: http://mydomain.com

Can I submit a PR to add support for this?

Thanks!

eladnava commented 8 years ago

Nevermind, apparently sending multiple Access-Control-Allow-Origin headers goes against the CORS spec.

The same functionality can be achieved by specifying a generator function as the origin param for kcors:

var cors = require('kcors');

// Configure Koa to use kcors module with origin verification 
app.use(cors({origin: verifyOrigin}));

// Origin verification generator
function* verifyOrigin (ctx) {
    // Get requesting origin hostname
    var origin = ctx.headers.origin;

    // List of valid origins
    var validOrigins = ['http://localhost:3000', 'http://mydomain.com'];

    // Make sure it's a valid origin
    if (validOrigins.indexOf(origin) != -1) {
       // Set the header to the requested origin 
        ctx.set('Access-Control-Allow-Origin', origin);
    }        
}
andreasgrimm commented 8 years ago

@eladnava thanks for pointing me into the right direction, although (at least with @next version) it didn't work out of the box. Having looked at the tests and combining it with your informatin, this is what worked for me:

const validOrigins = [
  `http://localhost:${ requestingClientPort }`,
  'https://somedomain.com' ];

const config = {
  // ...
  cors: {
    // ...
    origin: verifyOrigin }};

app.use( cors( config.cors ))

function verifyOrigin ( ctx ) {
  const origin = ctx.headers.origin;
  if ( !originIsValid( origin )) return false;
  return origin;
}

function originIsValid ( origin ) {
  return validOrigins.indexOf( origin ) != -1;
}
eladnava commented 8 years ago

@andreasgrimm cool, thanks for sharing! 😄