How to Valid @Requestheader in Spring Boot

Spring Boot APIs -Validate request header values

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>

Spring boot: @Valid not working with @RequestHeader

You are definitely supposed to use @Validated in your controller class, as it indicates that the validation is meant to be performed in that class. From the documentation:

To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation, which can optionally also declare the validation groups to use.

And, as you are using @Pattern (which is a Bean Validation annotation), you don't need @Valid.

Validate request headers with Spring validation framework

To check the presence of a request header, you don't need the validation framework. Request header parameters are mandatory by default, and if a mandatory header is missing in a request, Spring MVC automatically responds with 400 Bad Request.

So the following code automatically checks the presence of the header "Header-Name"...

@PostMapping("/action")
public ResponseEntity<String> doAction(@RequestHeader("Header-Name") String headerValue) {
// ...
}

... and if the header shall be optional, the annotation would need to be replaced by:

@RequestHeader(name = "Header-Name", required = false)

To check the value of a request header, the Spring validation framework can be used. To do this, you need to

  1. Add @Validated to the controller class. This is a workaround needed until this feature is implemented.
  2. Add the JSR-303 annotation to the request header parameter, e.g.

    @RequestHeader("Header-Name") @Pattern(regexp = "[A-Za-z]*") String headerValue

Note however that this will result in a 500 in case of an invalid header value. Check this question for how to also get the correct status code (i.e. 400) for this case.

Validate a HTTP-Header field in a Spring RestController

Basically the easiest (and most logical) way is to catch the Request before it gets to your Controller. That can be achieved either with a HandlerInterceptor as the other answer states or with a simple Filter like OncePerRequestFilter.

Extend that class, override the doFilterInternal() method as doFilter() is final, extract the proper header value, check it against whatever you need and depending on the value, either throw an Exception or continue with the chain.



Related Topics



Leave a reply



Submit