简体   繁体   中英

Java Spring rest return unauthorized json

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

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.

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

    } 

You just need to change your return type to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM