Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    } 
like image 732
user2524908 Avatar asked Dec 02 '22 16:12

user2524908


1 Answers

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.

like image 52
Darshan Patel Avatar answered Dec 15 '22 18:12

Darshan Patel