Question

I am writing a REST based web service. I need to return all the responses as JSON format. I have an interceptor to validate my authentication parameters. On authentication failure scenario, I have to return the error response in JSON format.

Currently i am doing

response.setHeader("Content-Type","application/json"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "{\"error\":\"Missing Authentication Parameters\"}");

The response body is coming as below.

JBoss Web/2.1.3.GA - Error report

HTTP Status 401 - {"error":"Missing Authentication Parameters"}

type Status report

message {"error":"Missing Authentication Parameters"}

description This request requires HTTP authentication ({"error":"Missing Authentication Parameters"}).

JBoss Web/2.1.3.GA

I need just the JSON string in response. Please help me.

Was it helpful?

Solution

You should probably be using spring-security for this. If you want to do it by hand, an alternative to using sendError on the response is to use spring MVC's @ExceptionHandler along with content negotiation to return JSON.

First define an error class*:

public class Error {
    public message;
    public exception;
    public Error(String message, Exception ex) {
        this.message = message;
        this.exception = ex;
    }
}

And an exception:

public class NotAuthenticatedException extends Exception {
    // ...
}

Then in your controller you throw an exception at the appropriate time, catch it with @ExceptionHandler and return a ResponseEntity containing an Error instance and the appropriate error code.

@Controller
public class SimpleController {
    @RequestMapping(...)
    public String aMethod() {
        // ...
        throw new NotAuthenticatedException("Missing Authentication Parameters");
    }

    @ExceptionHandler(NotAuthenticatedException.class)
    public ResponseEntity<Error> handleNotAuthenticatedException(
            NotAuthenticatedException ex, 
            HttpServletRequest request) {
        return new ResponseEntity<Error>(
            new Error(ex.getMessage(), ex), 
            HttpStatus.UNAUTHORIZED
        );
    }
}

*use getters/setters to please the java convention gods

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top