如何在 dto 属性上使用 SafeHtml 注释?
How to use SafeHtml annotation on dto properties?
我有一个 dto,它取自另一个 API(反编译 class),在那个 dto 中,一个字符串字段被标记为 SafeHtml,以防止用户注入 HTML 脚本。
@NotNull
@SafeHtml(
whitelistType = WhiteListType.NONE,
groups = {Default.class}
)
@ApiModelProperty(
value = "The label of customer",
required = true
)
private String label;
但是当我通过邮递员或从前端发送请求时 - 例如 <script>alert('blabla')</script>
- 它仍然接受此输入并执行。
这里似乎有什么问题?其他工作示例是项目自己的 dto class,但在这个示例中,这个 dto 是从另一个 api 反编译的 class,所以这可能是它的原因吗? (我不这么认为,因为这个 dto 的 api 也在接受它)那么有什么问题吗?
或者仅仅指定 SafeHtml 还不够,我需要做更多的事情吗?
编辑:我的控制器是:
@PostMapping("customer/save")
@ApiOperation("Adds customer")
public ResponseEntity<CustomerDto> saveCustomer(
@ApiParam("Customers to save") @RequestBody CustomerDti customerDto) {
return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}
注意:如果我将 safehtml 放在我的模型上 class,它可以工作,但我不想要它。我想在请求到来时立即拒绝它,所以我需要在 dto class.
上禁用它
如上所述,约束注释已验证 "on demand"。
在您的情况下,您必须添加 @Valid
注释以使请求有效:
@PostMapping("customer/save")
@ApiOperation("Adds customer")
public ResponseEntity<CustomerDto> saveCustomer(
@ApiParam("Customers to save") @RequestBody @Valid CustomerDti customerDto) {
return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}
我有一个 dto,它取自另一个 API(反编译 class),在那个 dto 中,一个字符串字段被标记为 SafeHtml,以防止用户注入 HTML 脚本。
@NotNull
@SafeHtml(
whitelistType = WhiteListType.NONE,
groups = {Default.class}
)
@ApiModelProperty(
value = "The label of customer",
required = true
)
private String label;
但是当我通过邮递员或从前端发送请求时 - 例如 <script>alert('blabla')</script>
- 它仍然接受此输入并执行。
这里似乎有什么问题?其他工作示例是项目自己的 dto class,但在这个示例中,这个 dto 是从另一个 api 反编译的 class,所以这可能是它的原因吗? (我不这么认为,因为这个 dto 的 api 也在接受它)那么有什么问题吗?
或者仅仅指定 SafeHtml 还不够,我需要做更多的事情吗?
编辑:我的控制器是:
@PostMapping("customer/save")
@ApiOperation("Adds customer")
public ResponseEntity<CustomerDto> saveCustomer(
@ApiParam("Customers to save") @RequestBody CustomerDti customerDto) {
return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}
注意:如果我将 safehtml 放在我的模型上 class,它可以工作,但我不想要它。我想在请求到来时立即拒绝它,所以我需要在 dto class.
上禁用它如上所述,约束注释已验证 "on demand"。
在您的情况下,您必须添加 @Valid
注释以使请求有效:
@PostMapping("customer/save")
@ApiOperation("Adds customer")
public ResponseEntity<CustomerDto> saveCustomer(
@ApiParam("Customers to save") @RequestBody @Valid CustomerDti customerDto) {
return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}