CarbonMan
CarbonMan

Reputation: 4490

Missing header 'Authorization' of type [java.lang.String]

I have a client app that communicates to the spring server with REST type calls using basic authentication. The controller method signature is below:

    @RequestMapping(value = "/REST/clients", method = RequestMethod.POST)
protected ModelAndView postClients(@ModelAttribute("ClientsCommand") ClientsCommand cmd,
        @RequestHeader("Authorization") String credentials) throws IOException {
...
}

The problem I have is that if no Authorization is present in the header I get an error:

Missing header 'Authorization' of type [java.lang.String]]

Whereas, I was kind of hoping the credentials string would just be empty. How do I stop the error from occurring and just receive a blank string if no authorization header entry was sent?

Upvotes: 0

Views: 23954

Answers (1)

stevevls
stevevls

Reputation: 10853

Try toggling required=false on the @RequestHeader.

@RequestMapping(value = "/REST/clients", method = RequestMethod.POST)
protected ModelAndView postClients(@ModelAttribute("ClientsCommand") ClientsCommand cmd,
        @RequestHeader(value = "Authorization", required=false) String credentials) throws IOException {
...
}

When the @RequestHeader is configured as required, Spring won't map a request to your handler when the header isn't there. By making it optional, your handler will be invoked as you're hoping (i.e. regardless of the header's presence).

Upvotes: 10

Related Questions