CORS configuration with Restify

occasl picture occasl · Sep 17, 2013 · Viewed 7.7k times · Source

I'm seeing that the access-control-allow-origin header is by default being set to a wildcard whenever I do an HTTP GET against my CORS enabled Restify service. I would rather that it echo the Origin that I send since that is a best practice per OWASP. Any recommendations how I could do that? Tried default headers, formatters, etc. that's in the API docs, but no luck.

Here's what I do:

    var server = restify.createServer({
        name: 'People Data Service',
        version: '1.0.6'
    });        
        server.pre(wrapper(restify.pre.pause()));
        // Cleans up sloppy paths
        server.pre(wrapper(restify.pre.sanitizePath()));
        server.use(wrapper(restify.acceptParser(server.acceptable)));
        server.use(wrapper(restify.authorizationParser()));
        server.use(wrapper(restify.queryParser()));
        server.use(wrapper(restify.bodyParser()));
        server.use(wrapper(restify.CORS()));
    //    server.use(wrapper(restify.fullResponse()));

        // Needed this for OPTIONS preflight request: https://github.com/mcavage/node-restify/issues/284
        function unknownMethodHandler(req, res) {
            if (req.method.toUpperCase() === 'OPTIONS') {
                console.log('Received an options method request from: ' + req.headers.origin);
                var allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With', 'Authorization'];

                if (res.methods.indexOf('OPTIONS') === -1) {
                    res.methods.push('OPTIONS');
                }

                res.header('Access-Control-Allow-Credentials', false);
                res.header('Access-Control-Expose-Headers', true);
                res.header('Access-Control-Allow-Headers', allowHeaders.join(', '));
                res.header('Access-Control-Allow-Methods', res.methods.join(', '));
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                res.header('Access-Control-Max-Age', 1209600);

                return res.send(204);
            }
            else {
                return res.send(new restify.MethodNotAllowedError());
            }
        }
    server.on('MethodNotAllowed', wrapper(unknownMethodHandler));

Answer

Lyman Lai picture Lyman Lai · Sep 26, 2013

I do it like this on my restify base app:

    //setup cors
    restify.CORS.ALLOW_HEADERS.push('accept');
    restify.CORS.ALLOW_HEADERS.push('sid');
    restify.CORS.ALLOW_HEADERS.push('lang');
    restify.CORS.ALLOW_HEADERS.push('origin');
    restify.CORS.ALLOW_HEADERS.push('withcredentials');
    restify.CORS.ALLOW_HEADERS.push('x-requested-with');
    server.use(restify.CORS());

you need to use restify.CORS.ALLOW_HEADERS.push method to push the header u want into restify first, then using the CORS middleware to boot the CORS function.