user2524908 user2524908 -4 years ago 112
Java Question

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

}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download