Skip to content

Commit

Permalink
Send authentication error in body
Browse files Browse the repository at this point in the history
  • Loading branch information
NikhilCollooru committed Aug 12, 2024
1 parent 6b02012 commit 4e91e2f
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,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 @@ -37,6 +38,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 @@ -102,7 +104,18 @@ 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 static ServletRequest withPrincipal(HttpServletRequest request, Principal principal)
Expand Down

0 comments on commit 4e91e2f

Please sign in to comment.