使用sails.js修改响应标头以实现HSTS [英] Modify response header with sails.js for implementing HSTS

查看:99
本文介绍了使用sails.js修改响应标头以实现HSTS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sails.js 实现nodejs应用程序.我希望我的用户仅通过https进行交流.因此,为此,我需要按照自己的方式配置服务器,以便在每个响应中添加一个标题"Strict-Transport-Security","max-age = 31536000",以告知浏览器仅与HSTS进行通信. 现在如何修改将要从Sails js发送的每个响应标头.我搜索了文档,但没有找到任何帮助.

I am implementing a nodejs application using sails.js. I want my user to communicate only through https. So for doing that I need to configure my server my way so that with each response it will add a header "Strict-Transport-Security", "max-age=31536000" to tell browser to communicate with HSTS only. Now how I can modify every response header that I am going to send from sails js.I searched the documentation but did not found any help.

推荐答案

策略仅应用于在config/policies.js中显式分配给它们的控制器.

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

而不是使用策略,请尝试直接在config/express.js中添加快速中间件(如果尚不存在,请创建文件).该中间件适用于 ALL 控制器.格式如下:

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!');
    }
};

如果您尝试让多个文件在'express.customMiddleware'命名空间上导出一个功能,我相信只有最后加载的文件的middleWare可以工作.我还没有尝试过.

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.

这篇关于使用sails.js修改响应标头以实现HSTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆