简体   繁体   中英

How to use SafeHtml annotation on dto properties?

I have a dto which is taken from another API (decompiled class) and in that dto one string field is tagged as SafeHtml to prevent users to inject HTML scripts.

@NotNull
@SafeHtml(
    whitelistType = WhiteListType.NONE,
    groups = {Default.class}
)
@ApiModelProperty(
    value = "The label of customer",
    required = true
)
private String label;

But when i send request via postman or from frontend -eg <script>alert('blabla')</script> - it still accepts this input and executes.

What seems wrong here? Other working examples are own dto class of the project but in this example this dto is a decompiled class from another api, so can it be the reason for it? (I don't think so because this dto's api is also accepting it) so what is wrong?

Or is only specifying SafeHtml not enough and do I need to do something more?

Edit: my controller is:

        @PostMapping("customer/save")
            @ApiOperation("Adds customer")
            public ResponseEntity<CustomerDto> saveCustomer(
                    @ApiParam("Customers to save") @RequestBody CustomerDti customerDto) {

    return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}

And note: if i put safehtml on my model class, it works but i do not want it. I want to reject the request immediately whenever it comes so i need to disable it on dto class.

As said, constraint annotations are validated "on demand".
In your case you have to add the @Valid annotation to valid the request :

@PostMapping("customer/save")
@ApiOperation("Adds customer")
public ResponseEntity<CustomerDto> saveCustomer(
        @ApiParam("Customers to save") @RequestBody @Valid CustomerDti customerDto) {

  return ResponseEntity.ok(customerService.saveCustomer(customerDto);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM