From 2f4352bd0c5376efc3873591ee3a675b30371e0b Mon Sep 17 00:00:00 2001 From: Nikhil Collooru Date: Thu, 8 Aug 2024 14:56:00 -0700 Subject: [PATCH] Send authentication error in body --- .../airlift/http/server/AuthenticationFilter.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/http-server/src/main/java/com/facebook/airlift/http/server/AuthenticationFilter.java b/http-server/src/main/java/com/facebook/airlift/http/server/AuthenticationFilter.java index a58064419b..0b303b11a3 100644 --- a/http-server/src/main/java/com/facebook/airlift/http/server/AuthenticationFilter.java +++ b/http-server/src/main/java/com/facebook/airlift/http/server/AuthenticationFilter.java @@ -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; @@ -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; @@ -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)