Reputation: 871
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);
}
}
Upvotes: 7
Views: 29702
Reputation: 2899
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.
Upvotes: 22