Java Spring rest返回未经授权的json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31948300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:23:58  来源:igfitidea点击:

Java Spring rest return unauthorized json

javajsonspringrestspring-mvc

提问by user2524908

Currently have a java spring application in development. It utilizes a ui along with restful apis which send/receive json via post requests.

目前有一个 java spring 应用程序正在开发中。它利用一个 ui 以及通过 post 请求发送/接收 json 的restful api。

Each api request needs to be validated with a token which will be sent with the request. This action is completed and a boolean is returned. Now the problem is when the boolean value is false(token not valid) I need to return a 401 error to the end user. Currently I am returning List which is being converted to json. How can I return some 401 error to the end user.

每个 api 请求都需要使用令牌进行验证,该令牌将与请求一起发送。此操作完成并返回一个布尔值。现在的问题是当布尔值为 false(令牌无效)时,我需要向最终用户返回 401 错误。目前我正在返回正在转换为 json 的列表。如何向最终用户返回一些 401 错误。

Example

例子

   //done
    @RequestMapping(value = "/getSomething"
            , method = RequestMethod.POST
            , consumes = "application/json"
            , produces = "application/json")
    @ResponseBody
    public List<Obj> getSomething(@RequestBody Input f) {

        DAOImpl dAOImpl = (MapDAOImpl) appContext.getBean("DAOImpl");

        Boolean res =  dAOImpl.validateToken(f.session);
        if(res) {
            List<Obj> response = dAOImpl.getSomething(f.ID);
            return response;
        } else {

            return new ResponseEntity<String>("test", HttpStatus.UNAUTHORIZED);
        }

    } 

回答by Darshan Patel

You just need to change your return type to ResponseEntity.

您只需要将返回类型更改为ResponseEntity.

@RequestMapping(value = "/getSomething"
        , method = RequestMethod.POST
        , consumes = "application/json"
        , produces = "application/json")
@ResponseBody
public ResponseEntity<?> getSomething(@RequestBody Input f) {

    DAOImpl dAOImpl = (MapDAOImpl) appContext.getBean("DAOImpl");

    Boolean res =  dAOImpl.validateToken(f.session);
    if(res) {
        List<Obj> response = dAOImpl.getSomething(f.ID);
        return new ResponseEntity<>(response, HttpStatus.OK);
    } 
    return new ResponseEntity<String>("Unauthorized", HttpStatus.UNAUTHORIZED);
} 

Note : I would recommend to pass proper JSON in error response so that client can parse and use if required.

注意:我建议在错误响应中传递正确的 JSON,以便客户端可以在需要时解析和使用。