Skip to content

Commit

Permalink
Send authentication error in body
Browse files Browse the repository at this point in the history
  • Loading branch information
electrum committed Jan 7, 2020
1 parent 189d906 commit c0bcc9b
Showing 1 changed file with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.LinkedHashSet;
import java.util.List;
Expand All @@ -40,6 +41,7 @@
import static com.google.common.io.ByteStreams.copy;
import static com.google.common.io.ByteStreams.nullOutputStream;
import static com.google.common.net.HttpHeaders.WWW_AUTHENTICATE;
import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;
import static java.util.Objects.requireNonNull;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;

Expand Down Expand Up @@ -76,7 +78,8 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
if (internalAuthenticationManager.isInternalRequest(request)) {
Principal principal = internalAuthenticationManager.authenticateInternalRequest(request);
if (principal == null) {
response.sendError(SC_UNAUTHORIZED);
response.setStatus(SC_UNAUTHORIZED);
response.setContentType(PLAIN_TEXT_UTF_8.toString());
return;
}
nextFilter.doFilter(withPrincipal(request, principal), response);
Expand Down Expand Up @@ -121,7 +124,19 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
if (messages.isEmpty()) {
messages.add("Unauthorized");
}
response.sendError(SC_UNAUTHORIZED, Joiner.on(" | ").join(messages));

// The error string is used by clients for exception messages and
// is presented to the end user, thus it should be a single line.
String error = Joiner.on(" | ").join(messages);

// Clients should use the response body rather than the HTTP status
// message (which does not exist with HTTP/2), but the status message
// still needs to be sent for compatibility with existing clients.
response.setStatus(SC_UNAUTHORIZED, error);
response.setContentType(PLAIN_TEXT_UTF_8.toString());
try (PrintWriter writer = response.getWriter()) {
writer.write(error);
}
}

private boolean doesRequestSupportAuthentication(HttpServletRequest request)
Expand Down

0 comments on commit c0bcc9b

Please sign in to comment.