Monday, 12 June 2017

Implement helmet-csp on individual routes

I'm creating a sample Express app to demonstrate Content-Security-Policy (CSP) headers and am trying to use helmet-csp.

All of the documentation for helmet-csp shows it used as standard third-party-middleware via app.use(csp({ ... })) - this adds the CSP headers to every route in my application, but I want to customize it on individual routes.

Sample App

var express = require('express');
var http = require('http');
var csp = require('helmet-csp');
var app = express();

app.use(csp({
    directives: {
        frameSrc: ["'none'"]
    }
}));

app.get('/', (request, response) => {
    response.send('hi, :wave: =]');
});

app.get('/frameable', (request, response) => {
    response.send('you can frame me!');
});

http.createServer(app).listen(80, (err) => {
    if (err) {
        return console.log('error', err);
    }
});

With the above, every route receives the CSP header:

Content-Security-Policy: frame-src 'none'

In the /frameable route, I would want to override this CSP header to be:

Content-Security-Policy: frame-src 'self'

Whenever I need/want to customize a header set by helmet-csp on a per-route basis, do I need to manually override them inside each app.get with a line such as:

response.setHeader('Content-Security-Policy', "frame-src 'self'");

Or is there a way to do this via helmet-csp itself?



via newfurniturey

No comments:

Post a Comment