Openapi
安全
了解如何在 NestJS 中使用 @nestjs/swagger 定义 OpenAPI 安全机制,包括基本认证、Bearer 认证、OAuth2 和 Cookie 认证
安全
要定义特定操作应使用哪些安全机制,请使用 @ApiSecurity() 装饰器。
@ApiSecurity('basic')
@Controller('cats')
export class CatsController {}
在运行应用程序之前,请记住使用 DocumentBuilder 将安全定义添加到基础文档中:
const options = new DocumentBuilder().addSecurity('basic', {
type: 'http',
scheme: 'basic',
});
一些最流行的身份验证技术是内置的(例如,basic 和 bearer),因此您不必像上面所示的那样手动定义安全机制。
基本认证
要启用基本认证,请使用 @ApiBasicAuth()。
@ApiBasicAuth()
@Controller('cats')
export class CatsController {}
在运行应用程序之前,请记住使用 DocumentBuilder 将安全定义添加到基础文档中:
const options = new DocumentBuilder().addBasicAuth();
Bearer 认证
要启用 Bearer 认证,请使用 @ApiBearerAuth()。
@ApiBearerAuth()
@Controller('cats')
export class CatsController {}
在运行应用程序之前,请记住使用 DocumentBuilder 将安全定义添加到基础文档中:
const options = new DocumentBuilder().addBearerAuth();
OAuth2 认证
要启用 OAuth2,请使用 @ApiOAuth2()。
@ApiOAuth2(['pets:write'])
@Controller('cats')
export class CatsController {}
在运行应用程序之前,请记住使用 DocumentBuilder 将安全定义添加到基础文档中:
const options = new DocumentBuilder().addOAuth2();
Cookie 认证
要启用 Cookie 认证,请使用 @ApiCookieAuth()。
@ApiCookieAuth()
@Controller('cats')
export class CatsController {}
在运行应用程序之前,请记住使用 DocumentBuilder 将安全定义添加到基础文档中:
const options = new DocumentBuilder().addCookieAuth('optional-session-id');