2

Can we make a header parameter mandatory but not the value using @RequestHeader?

For example if we use,

@RequestHeader(value = "abc", required = true) 

both parameter and it value has to be there.

Edit: Suppose i call some rest api has above request header param with "abc" but no value. So in this case i am able to invoke the rest api successfully since i have invoke with "abc" header param even i did not enter a value to it. Due to some governance tool rule, i need to have a specific header param but i dont want force user to enter any value.

Harshana
  • 7,297
  • 25
  • 99
  • 173

2 Answers2

5

Spring 5.2 and lower

The @RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.

Given below are the available fields as per Spring Doc

  • defaultValue: The default value to use as a fallback.
  • name: The name of the request header to bind to.
  • required: Whether the header is required; null values are allowed
  • value: Alias for name()

So what you can do is read the parameter either with the help of @RequestHeader or inject a HttpServletRequest request, read by request.getHeader(...) and check inside the controller method if the value exists and then can call methods to perform the necessary logic.

Although you can make sure that the parameter exists with the help of required attribute for e.g. @RequestHeader(value = "Authorization", required = true) String authorization).

Spring 5.3+

The required field was tightened up, both the property and the value should exist. From the release notes:

The @RequestHeader annotation detect a null conversion result value and treat it as missing. In order to allow an empty value to be injected as a null argument, either set required=false on the argument annotation, e.g. @RequestParam(required=false), or declare the argument as @Nullable.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Mudassar
  • 3,135
  • 17
  • 22
  • yes. in this if user does not enter value for Authorization it wont go inside the cotroller method and throw 400 bad request – Harshana Jun 22 '16 at 13:01
  • updated in the solution to read the header data from request object instead or replying on the @RequestHeader – Mudassar Jun 22 '16 at 13:05
2

As @Mudassar said, @RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.

It is related to this issue: https://github.com/spring-projects/spring-framework/issues/23939

I developed a workaround for this problem using an annotation @RequestHeaderNonNull that I've created: https://github.com/armandoalmeida/request-header-required-non-null

I hope I've helped you!