安全防护,我们主要从:
- 基本防护如 helmet, 通过修改 http 头的方式进行防护
- CORS 就是我们常见的跨域
- CSRF 伪造站点攻击
- 限速
helmet
import * as helmet from 'helmet';
app.use(helmet());
import * as helmet from 'fastify-helmet';
app.register(helmet);
CORS
// 使用中间件的方式
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
// 使用 app 配置项的方式
const app = await NestFactory.create(AppModule, { cors: true });
await app.listen(3000);
配置项:
- origin
- methods
- allowedHeaders
- exposedHeaders
- credentials
- maxAge
- preflightContinue
- optionsSuccessStatus
CSRF
import * as csurf from 'csurf';
app.use(csurf());
限速
安装:
yarn add express-rate-limit
使用:
import * as rateLimit from 'express-rate-limit';
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
}),
);
// see https://expressjs.com/en/guide/behind-proxies.html
app.set('trust proxy', 1);