常用的Express中间件helmet:提供各种安全增强功能

下面是使用 Helmet 中间件的示例代码,包括了一些常见的安全增强功能:

const express = require('express');
const helmet = require('helmet');

const app = express();

// 使用 Helmet 中间件
app.use(helmet());

// 禁止客户端缓存
app.use((req, res, next) => {
  res.set('Cache-Control', 'no-store');
  next();
});

// 设置 Content Security Policy
app.use((req, res, next) => {
  res.set('Content-Security-Policy', "default-src 'self'");
  next();
});

// 禁止页面被嵌入到 iframe 中
app.use((req, res, next) => {
  res.set('X-Frame-Options', 'SAMEORIGIN');
  next();
});

// 禁止浏览器将站点内容嵌入到其他站点
app.use((req, res, next) => {
  res.set('X-XSS-Protection', '1; mode=block');
  next();
});

// 启用 HTTP Strict Transport Security
app.use((req, res, next) => {
  res.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  next();
});

// 禁止浏览器将站点内容预加载
app.use((req, res, next) => {
  res.set('X-DNS-Prefetch-Control', 'off');
  next();
});

// 禁止浏览器发送 Referer 头信息
app.use((req, res, next) => {
  res.set('Referrer-Policy', 'no-referrer');
  next();
});

// 处理其他中间件
// ...

app.listen(3000, () => {
  console.log('App started on port 3000');
});

这段代码使用了 Helmet 中间件,并且设置了禁止客户端缓存、Content Security Policy、X-Frame-Options、X-XSS-Protection、HTTP Strict Transport Security、X-DNS-Prefetch-Control、Referrer-Policy 等安全增强功能。