如何在instanceToPlain时排除属性,plainToInstance时保留
解决IntegrationDto令牌字段泄露问题
1. 隐藏Swagger文档中的敏感字段
你的现有代码已通过@Expose({ toClassOnly: true })确保序列化时不输出令牌字段,但Swagger仍可能识别并展示这些字段。给accessToken、expiresIn、refreshToken添加@ApiHideProperty()装饰器,即可在API文档中隐藏它们:
import { ApiHideProperty } from '@nestjs/swagger'; export class IntegrationDto extends BaseDto { @ApiProperty({ enum: Object.values(IntegrationType), description: 'Type of the integration' }) @Expose() name: IntegrationType; @ApiProperty({ description: 'Timestamp of the last synchronization' }) @Expose() lastSyncAt?: Date; @ApiHideProperty() @Expose({ toClassOnly: true }) accessToken: string; @ApiHideProperty() @Expose({ toClassOnly: true }) @Transform(({ value }) => value instanceof Timestamp && value.toDate(), { toClassOnly: true }) expiresIn?: Date; @ApiHideProperty() @Expose({ toClassOnly: true }) refreshToken?: string; @ApiProperty({ type: IntegrationProfileDto, description: 'Profile information' }) @Type(() => IntegrationProfileDto) @ValidateNested() @Expose() profile: IntegrationProfileDto; @ApiProperty({ description: 'Metadata associated with the integration', required: false }) @Expose() metadata?: Record<string, unknown>; }
2. 确认全局序列化配置
确保NestJS全局验证管道启用excludeExtraneousValues,让class-transformer严格按照@Expose规则序列化对象,只输出标记的字段:
// main.ts import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ transform: true, excludeExtraneousValues: true, // 仅保留@Expose标记的字段 })); await app.listen(3000); } bootstrap();
核心逻辑说明
@Expose({ toClassOnly: true }):仅在请求转DTO实例阶段解析这些字段,当DTO实例转响应JSON时自动排除,保证内部使用时能访问令牌,网络响应中不暴露。@ApiHideProperty():移除Swagger文档中这些敏感字段的展示,避免API文档泄露令牌信息。excludeExtraneousValues: true:全局层面强制序列化规则,防止未标记@Expose的字段意外泄露。
内容的提问来源于stack exchange,提问作者tbhaxor
相关产品推荐
相关产品推荐

