glhr
glhr

Reputation: 417

Spring - returning a non-revealing response in case of bad credentials

I am using Spring Boot for a REST API. I have the following AuthenticationEntryPoint:

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

This returns a 401 Response with the following body in case of bad credentials:

{
  "timestamp": 1464883746518,
  "status": 401,
  "error": "Unauthorized",
  "exception": "org.springframework.security.authentication.BadCredentialsException",
  "message": "Unauthorized",
  "path": "/webapp/login"
}

I find that the 'exception' field gives up too much information (f.i. that I'm using spring security) - ideally I'd like to hide that from the response.

How should I best return a less-revealing message? My initial thinking is to throw a custom exception and handle it by returning a new ResponseEntity(HttpStatus.UNAUTHORIZED) from a @ControllerAdvice?

Is there a better (maybe standardized) way to return more generic error messages?

Upvotes: 1

Views: 1247

Answers (2)

Ali Dehghani
Ali Dehghani

Reputation: 48133

Register a new ErrorAttributes and remove the exception field from the error responses:

@Component
class ApiErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> attributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
        attributes.remove("exception");

        return attributes;
    }
}

Upvotes: 1

gnasher729
gnasher729

Reputation: 52538

A status 401 should contain information what kind of authentication is required, and nothing else.

Upvotes: 0

Related Questions