【问题标题】:Missing request header 'authToken' calling RestAPI method缺少调用 RestAPI 方法的请求标头“authToken”
【发布时间】:2019-01-15 09:19:06
【问题描述】:

我有这个 RestAPI 方法

@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));

    }

我从 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"

但是我收到了这个错误:

   "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....

【问题讨论】:

    标签: rest spring-boot resttemplate restful-authentication


    【解决方案1】:

    你不能那样使用@RequestHeader。标头中的值被 : 拆分并添加到 Map,因此每个包含 : 的值都是不可能的。

    您必须将注释更改为@RequestHeader(value="Authorization"),然后从authToken 中删除Bearer

    【讨论】:

      【解决方案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 .
      

      【讨论】:

        猜你喜欢
        • 2018-10-31
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 1970-01-01
        • 2015-11-08
        • 2018-02-03
        相关资源
        最近更新 更多