Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 7, 2018 14:33
Show Gist options
  • Save slmanju/090a0b9ffbd638de08c85150c899c402 to your computer and use it in GitHub Desktop.
Save slmanju/090a0b9ffbd638de08c85150c899c402 to your computer and use it in GitHub Desktop.
public class UnauthorizedHandler implements AuthenticationEntryPoint {
private ObjectMapper mapper = new ObjectMapper();
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authenticationException)
throws IOException, ServletException {
String authorizationToken = request.getHeader(HttpHeaders.AUTHORIZATION);
String message = (authorizationToken != null) ? "Invalid token" : authenticationException.getMessage();
ErrorResponse errorResponse = ErrorResponse.builder()
.errorCode(HttpServletResponse.SC_UNAUTHORIZED)
.errorMessage(message).build();
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().println(mapper.writeValueAsString(errorResponse));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment