Modify response header with sails.js for implementing HSTS

狂风中的少年 提交于 2019-12-04 05:43:44

Policies are only applied to the controllers that you explicitly assign them to in config/policies.js.

Instead of using a policy, try adding an express middleware directly in config/express.js, (create the file if it does not already exist). This middleware is applied to ALL controllers. The format is like so:

// config/express.js
"use strict";
exports.express = {
    customMiddleware: function (app) {
        app.use(function hsts(req, res, next) {
            res.setHeader("Strict-Transport-Security", "max-age=31536000");
            next();
        });
    }
}

If you have multiple express custom middleware that you want to use, my advice is to keep each middleware function in its own file. I will provide an example, using your middleware along with an additional middleware that accepts some options.

// config/express.js
"use strict";
var hsts = require('../lib/middleware/hsts');
var staticguard = require('../lib/middleware/staticguard');
exports.express = {
    customMiddleware: function (app) {
        // ordering of middleware matters!
        app.use(hsts);
        app.use(staticguard(/^\/protected\/.*$/));
    }
}

// lib/middleware/hsts.js
"use strict";
module.exports = function hsts(req, res, next) {
    res.setHeader("Strict-Transport-Security", "max-age=31536000");
    next();
}

// lib/middleware/staticguard.js
"use strict";
module.exports = function (regex) {
    return function (req, res, next) {
        if (!regex.test(req.url)) {
            return next();
        }
        res.end('you are not allowed!');
    }
};

If you try to have multiple files export a function on the 'express.customMiddleware' namespace, I believe only the middleWare of the last file loaded will work. I haven't tried it though.

You should be able to use Sails policies. With this you should be able to create a policy to change the headers being sent back.

// policies/hsts.js
module.exports = function hsts(req, res, next) {
  res.setHeader("Strict-Transport-Security", "max-age=31536000");
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!