6

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

    } 
2
  • 2
    Generally, I'd just throw an exception annotated with @ResponseStatus. Aug 11, 2015 at 17:32
  • 1
    You should always return "ResponseEntity" - in the first case return ResponseEntity with body - List<Obj> and status 200; in the second case: either return ResponseEntity with body empty list and status 401 or throw exception as suggested in the previous comment. Aug 11, 2015 at 17:48

1 Answer 1

21

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.

1
  • That seems to work. I appreciate the recommendation about always using Responseentity Aug 11, 2015 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.