webAPI 安全保护

110 阅读1分钟

限速Throttler插件

NestJS提供了强大的Throttler模块,用于构建抗DDoS攻击和防止滥用的应用程序。这款模块旨在限制请求频率,保护你的服务免受恶意或过量访问。

安装

$ npm i --save @nestjs/throttler

使用

使用 forRoot 或 forRootAsync 方法将 ThrottlerModule 配置为任何其他 Nest 包。

//app.module.ts
@Module({
  imports: [
    ThrottlerModule.forRoot([{
      ttl: 60000,//毫秒
      limit: 10,
    }]),
  ],
  providers: [{
    provide: APP_GUARD,
    useClass: ThrottlerGuard,
  }],
})
export class AppModule {}

将为受保护的应用的路由设置 ttl(生存时间(以毫秒为单位))和 limit(ttl 内的最大请求数)的全局选项。

多个节流阀定义

有时你可能需要设置多个限制定义,例如每秒不超过 3 个调用、10 秒内不超过 20 个调用以及一分钟不超过 100 个调用。为此,你可以使用命名选项在数组中设置定义,稍后可以在 @SkipThrottle() 和 @Throttle() 装饰器中引用这些定义以再次更改选项。

@Module({
  imports: [
    ThrottlerModule.forRoot([
      {
        name: 'short',
        ttl: 1000,
        limit: 3,
      },
      {
        name: 'medium',
        ttl: 10000,
        limit: 20
      },
      {
        name: 'long',
        ttl: 60000,
        limit: 100
      }
    ]),
  ],
})
export class AppModule {}

装饰器

@SkipThrottle() 装饰器可以用来跳过一个路由或一个类

@SkipThrottle()
@Controller('users')
export class UsersController {}

@Throttle() 装饰器,可用于覆盖全局模块中设置的 limit 和 ttl,以提供更严格或更宽松的安全选项。

// Override default configuration for Rate limiting and duration.
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
  return "List users works with custom rate limiting.";
}

跨源资源共享 (CORS)

跨源资源共享 (CORS) 是一种允许从另一个域请求资源的机制。在底层,Nest 根据底层平台使用 Express cors 或 Fastify @fastify/cors 软件包。这些软件包提供了各种选项,你可以根据你的要求进行自定义。

入门

要启用 CORS,请在 Nest 应用对象上调用 enableCors() 方法。

const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);

通过 create() 方法的选项对象启用 CORS

const app = await NestFactory.create(AppModule, { cors: true });
await app.listen(3000);

Helmet

Helmet 可以通过适当设置 HTTP 标头来帮助保护你的应用免受一些众所周知的 Web 漏洞的侵害。一般来说,Helmet 只是一些较小的中间件函数的集合,它们设置与安全相关的 HTTP 标头(阅读 more)。

与 Express 一起使用(默认)

安装

$ npm i --save helmet

main.ts

import helmet from 'helmet';
// somewhere in your initialization file
app.use(helmet());

CSRF 保护

跨站点请求伪造(也称为 CSRF 或 XSRF)是一种对网站的恶意利用,其中 Web 应用信任的用户传输未经授权的命令。要减轻这种攻击,你可以使用 csurf 包。

安装

$ npm i --save csurf

main.ts

import * as csurf from 'csurf';
// ...
// somewhere in your initialization file
app.use(csurf());