How to exclude entity field from returned by controller JSON. NestJS + Typeorm

前端 未结 7 1597
小蘑菇
小蘑菇 2020-12-06 05:26

I want to exclude password field from returned JSON. I am using NestJS and Typeorm.

The solution provided on this question doesn\'t work for me or in NestJS. I can

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 05:43

    Lots of good answers in this thread. To build on apun's answer above, I think the following approach is the least likely to accidentally leak a password field:

    @Column({ select: false })
    password: string
    

    If the entity doesn't select that field by default, and it can only be explicitly queried (e.g. via addSelect() if using the query builder), I think it is a lot less likely that there's a slip somewhere, and there's less reliance on the "magic" of a framework (which is ultimately the class-transformer library) to ensure security. Realistically in many projects the only place you'd explicitly select it is where you check credentials.

    This approach can also help keep the password hash from accidentally leaking into log entries, etc, which is a consideration that hasn't been mentioned yet. It feels much safer to toss around the user object knowing that it doesn't include sensitive information, especially if it could end up serialized in a log entry somewhere.

    All said, the documented approach for NestJS is to use the @Exclude() decorator and the accepted answer is from the project's founder.

    I definitely make frequent use of the Exclude() decorator, but not necessarily for password or salt fields.

提交回复
热议问题