隐藏敏感信息作为回应

sha*_*nda 1 java rest spring spring-mvc spring-boot

我目前正在一个项目中工作,我有一个用户模型,并使用REST API来获取用户列表.(我有更多实体).

用户有密码字段.我不想在结果中包含密码字段.所以我把它排除在DTO之外.但是当我想创建一个用户时,我想在请求中包含密码.所以Spring MVC获得了User实体(而不是DTO).

我不认为这样做是好的....例如,我有一个事件模型,它连接到具有多对多关系的用户.我不希望在请求中.我只想要用户.那么你建议我做什么?有另一种DTO?

提前致谢.

Zic*_*ico 15

使用@JsonIgnoreAccess.WRITE_ONLY只有getter方法

@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Run Code Online (Sandbox Code Playgroud)


the*_*Guy 8

如果您使用 jackson 序列化您的响应对象,您可以使用 @JsonIgnore 注释有问题的属性,它不会包含在响应中。

public User {
    private String email;

    @JsonIgnore
    private String password

    ...getters and setters

}
Run Code Online (Sandbox Code Playgroud)

创建仅包含您想要的字段的单独响应对象也可能是一个好主意,以防您在路上添加敏感字段而忘记隐藏它们。同样,您也可以使用单独的请求对象来创建包含密码字段的用户。像用户这样的业务实体可能最好只在内部使用,这样您就可以控制公开哪些信息。


Raf*_*fal 6

为避免使用 @JsonIgnore,您可以使用json-view library。例如,在您的控制器中,您可以执行以下操作:

首先在您的控制器变量中声明:

private JsonResult json = JsonResult.instance();
Run Code Online (Sandbox Code Playgroud)

然后使用这个方法:

@RequestMapping("/get/{id}")
public void getUserById(@PathVariable(value = "id") long id) {
    User user = usersService.findOne(id);
    json.use(JsonView.with(user)
            .onClass(User.class, Match.match()
                    .exclude("password").exclude("yetAnothertopSecretField")));
}
Run Code Online (Sandbox Code Playgroud)

它返回没有排除字段的 JSON。

JsonView、JsonResult 类是从 json-view 库中导入的。


Abh*_*eet -2

在发送响应时将“密码”字段设置为空,杰克逊将不会在响应中显示该字段。不要将其从模型类中完全删除。