Home > Enterprise >  Spring Boot APIs -Validate request header values
Spring Boot APIs -Validate request header values

Time:04-05

I have a spring boot API which contains request headers , I want to validate those request headers for example i have given activity-id as header and set min and max properties as 3 , so its length should be 3. similarly i have added regex pattern also . I tried this along with @validated annotations in class level , But its not validating these constraints . Its allowing to hit API with activity-id with length greater than 3 . similarly i have around 10 headers to validate. Please guide how to validate request headers in spring boot API .

Its validating the request model and validating the header presents but not the headers values.

    @PostMapping(value = "/demo")
public ResponseEntity<TransactionResponse> doTransaction(
        @RequestBody @Valid TransactionRequest transactionRequest, final BindingResult bindingResult,
        @RequestHeader(value = "Authorization", required = true) String token,
        @RequestHeader(value = "activity-id") @Pattern(regexp = "^[0-9] $", message = "activity-id should be a 3-digit number.") @Size(min = 3, max = 3, message = "activity-id should be a 3-digit number.") String activityId)
        throws TransactionException, ValidationException {
        // implementation
}

CodePudding user response:

Use @Validated to the Controller class.

Something like this.

@Controller
@Validated //  <----  Add this
public class TestController {
@PostMapping(value = "/demo")
public ResponseEntity<TransactionResponse> doTransaction(
        @RequestBody @Valid TransactionRequest transactionRequest, final BindingResult bindingResult,
        @RequestHeader(value = "Authorization", required = true) String token,
        @RequestHeader(value = "activity-id") @Pattern(regexp = "^[0-9] $", message = "activity-id should be a 3-digit number.") @Size(min = 3, max = 3, message = "activity-id should be a 3-digit number.") String activityId)
        throws TransactionException, ValidationException {
        // implementation
}

CodePudding user response:

The issue is with the spring boot version , am using 2.4.9 and with version 2.3 Validation Starter no longer included in web starters , so we need to explicitly add the below validator dependency to work with the validations .

 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  • Related