Missing request header 'authToken' calling RestAPI method

丶灬走出姿态 提交于 2021-02-08 07:46:00

问题


I have this RestAPI method

@GetMapping(path = "/menus",
                consumes = "application/json", 
                produces = "application/json")
    public ResponseEntity<List<MenuPriceSummary>> allMenus(HttpServletRequest request,  @RequestHeader(value="Authorization: Bearer") String authToken) {

        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        User user = userService.findByUserName(username);
        return ResponseEntity.ok(menuService.allMenus(user));

    }

which I call from curl

curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsb3Blei5hbnRvbmlvODVAZ21haWwuY29tIiwiZXhwIjoxNTk0MTkzNDYwLCJpYXQiOjE1MzM3MsM0NjB9.9pXvdiRMM5fjE4Ur5nqKvwvRLmNWyn6tY6y5fPXOg_BWEW2sJ8vnrLTXPfiA-Sc6Qk2XTwi6FhlIhFEQKip4aQ"  "http://127.0.0.1:1133/canPeris/api/v1/users/menus"

But I got this error:

   "status":400,"error":"Bad Request","message":"Missing request header 'Authorization: Bearer' for method parameter of type String"'authToken' for method parameter of type String","tr....

回答1:


You can't use @RequestHeader that way. The values from the headers get split up by : and added to a Map, so every value containing a : is impossible.

You will have to change your annotation to @RequestHeader(value="Authorization") and then remove the Bearer from the authToken.




回答2:


Spring MVC provides annotation @RequestHeader that can be used to map controller parameter to request header value .

    Can you please change your method to 

    @GetMapping(path = "/menus",
                    consumes = "application/json", 
                    produces = "application/json")
    public ResponseEntity<List<MenuPriceSummary>> allMenus(
                @RequestHeader(value="Authorization") String authToken,
                HttpServletRequest request) {

              String username = jwtTokenUtil.getUsernameFromToken(authToken);
            User user = userService.findByUserName(username);
            return ResponseEntity.ok(menuService.allMenus(user));

        }

You can also make use of Interceptors to validate headers so that other rest endpoints in your application can make use of it .


来源:https://stackoverflow.com/questions/51741086/missing-request-header-authtoken-calling-restapi-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!