gpt4 book ai didi

security - Hapijs 在一个连接上同时使用 Http 和 Https

转载 作者:行者123 更新时间:2023-12-02 19:33:33 26 4
gpt4 key购买 nike

新加入Hapijs并尝试使用它来创建一个应用程序,该应用程序对所有请求使用 HTTPS 并将 HTTP 重定向到安全连接。问题是应用程序进入 HTTPS 模式没有问题,但如果我将 URL 更改为 HTTP,服务器不会响应并且不响应不知道原因。

这是我到目前为止想到的,它有效,但不适用于 HTTP

var connectionOptions = {
port: 3000,
tls: {
key: fs.readFileSync(path.join(__dirname, 'key/key.pem'), 'utf8'),
cert: fs.readFileSync(path.join(__dirname, 'key/cert.pem'), 'utf8')
}
};

var server = new Hapi.Server();
server.connection(connectionOptions);

//This method not called when its HTTP
server.ext('onRequest', function (request, reply) {
if (request.headers['x-forwarded-proto'] === 'http') {
reply.redirect('https://' + request.headers.host +
request.url.path).code(301);
return reply.continue();
}
reply.continue();
});

var routes = require('./routes')(server);
server.route(routes);

if (!module.parent) {
server.start(function () {
console.log('Server running at:', server.info.uri);
});
}

如何强制所有请求均为 HTTPS。谢谢您的帮助

最佳答案

您不能在同一连接上使用 http 和 https。在幕后,Hapi 将根据您的 tls 配置创建一个 Node http 服务器一个 https 服务器,如图所示在 lib/connection.js 的这一行中:

this.listener = this.settings.listener || (this.settings.tls ? Https.createServer(this.settings.tls) : Http.createServer());

您应该创建另一个不使用 TLS 的服务器连接,然后将非 TLS 请求重定向到 https 网址。

示例

const Hapi = require('hapi');
const Fs = require('fs');
const Url = require('url');

const config = {
host: 'localhost',
http: { port: 3001 },
https: {
port: 3000,
key: Fs.readFileSync('key.key'),
cert: Fs.readFileSync('cert.pem')
}
}

const server = new Hapi.Server();

// https connection

server.connection({
port: config.https.port,
tls: {
key: config.https.key,
cert: config.https.cert
}
});

// http connection

server.connection({ port: config.http.port });

server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {

reply('Hello world');
}
});

server.ext('onRequest', (request, reply) => {

if (request.connection.info.port !== config.https.port) {

return reply.redirect(Url.format({
protocol: 'https',
hostname: request.info.hostname,
pathname: request.url.path,
port: config.https.port
}));
}

return reply.continue();
});

server.start((err) => {

if (err) {
throw err;
}

console.log('Started server');
});

编辑

如果您在重定向到 HTTPS 之前允许与服务器的不安全连接,请考虑使用 HTTP Strict Transport Security (HSTS)以防止 MITM 攻击。您可以使用路由配置 security 选项设置 HSTS header :

server.route({
config: {
security: {
hsts: {
maxAge: 15768000,
includeSubDomains: true,
preload: true
}
}
},
method: 'GET',
path: '/',
handler: function (request, reply) {

...
}
});

关于security - Hapijs 在一个连接上同时使用 Http 和 Https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com