|
| 1 | +package com.digitalsanctuary.spring.user.security; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import org.springframework.security.core.AuthenticationException; |
| 5 | +import org.springframework.security.web.AuthenticationEntryPoint; |
| 6 | +import jakarta.servlet.ServletException; |
| 7 | +import jakarta.servlet.http.HttpServletRequest; |
| 8 | +import jakarta.servlet.http.HttpServletResponse; |
| 9 | +import lombok.extern.slf4j.Slf4j; |
| 10 | + |
| 11 | +/** |
| 12 | + * An {@link AuthenticationEntryPoint} that detects HTMX requests and returns a JSON 401 response instead of the |
| 13 | + * default 302 redirect to the login page. |
| 14 | + * |
| 15 | + * <p>When an HTMX-powered page has polling or dynamic fragment requests and the user's session expires, Spring |
| 16 | + * Security's default entry point sends a 302 redirect to the login page. HTMX transparently follows the redirect and |
| 17 | + * swaps the full login page HTML into each target element, breaking the UI. This entry point intercepts HTMX requests |
| 18 | + * (identified by the {@code HX-Request} header) and returns a 401 status with a JSON body and an {@code HX-Redirect} |
| 19 | + * header, allowing the HTMX client to handle the session expiry gracefully.</p> |
| 20 | + * |
| 21 | + * <p>Non-HTMX requests are delegated to the wrapped {@link AuthenticationEntryPoint}, preserving the existing |
| 22 | + * redirect behavior for standard browser requests.</p> |
| 23 | + * |
| 24 | + * @see <a href="https://htmx.org/attributes/hx-request/">HTMX HX-Request Header</a> |
| 25 | + * @see <a href="https://htmx.org/headers/hx-redirect/">HTMX HX-Redirect Response Header</a> |
| 26 | + */ |
| 27 | +@Slf4j |
| 28 | +public class HtmxAwareAuthenticationEntryPoint implements AuthenticationEntryPoint { |
| 29 | + |
| 30 | + static final String HX_REQUEST_HEADER = "HX-Request"; |
| 31 | + static final String HX_REDIRECT_HEADER = "HX-Redirect"; |
| 32 | + |
| 33 | + private final AuthenticationEntryPoint delegate; |
| 34 | + private final String loginUrl; |
| 35 | + |
| 36 | + /** |
| 37 | + * Creates a new HTMX-aware authentication entry point. |
| 38 | + * |
| 39 | + * @param delegate the entry point to delegate to for non-HTMX requests |
| 40 | + * @param loginUrl the login page URL used in the JSON response and HX-Redirect header |
| 41 | + */ |
| 42 | + public HtmxAwareAuthenticationEntryPoint(AuthenticationEntryPoint delegate, String loginUrl) { |
| 43 | + this.delegate = delegate; |
| 44 | + this.loginUrl = loginUrl; |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public void commence(HttpServletRequest request, HttpServletResponse response, |
| 49 | + AuthenticationException authException) throws IOException, ServletException { |
| 50 | + if (isHtmxRequest(request)) { |
| 51 | + log.debug("HTMX request detected for URI {}; returning 401 with JSON body and HX-Redirect to {}", |
| 52 | + request.getRequestURI(), loginUrl); |
| 53 | + |
| 54 | + if (response.isCommitted()) { |
| 55 | + log.warn("Response already committed for HTMX request to {}; cannot write 401 response", |
| 56 | + request.getRequestURI()); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + // Prepend the servlet context path so deployments with server.servlet.context-path work correctly. |
| 61 | + // LoginUrlAuthenticationEntryPoint does the same when building its redirect URL. |
| 62 | + String contextPath = request.getContextPath(); |
| 63 | + String fullLoginUrl = contextPath + loginUrl; |
| 64 | + |
| 65 | + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
| 66 | + response.setCharacterEncoding("UTF-8"); |
| 67 | + response.setContentType("application/json;charset=UTF-8"); |
| 68 | + response.setHeader(HX_REDIRECT_HEADER, fullLoginUrl); |
| 69 | + String escapedLoginUrl = fullLoginUrl |
| 70 | + .replace("\\", "\\\\") |
| 71 | + .replace("\"", "\\\"") |
| 72 | + .replace("\n", "\\n") |
| 73 | + .replace("\r", "\\r") |
| 74 | + .replace("\t", "\\t"); |
| 75 | + response.getWriter().write("{\"error\":\"authentication_required\"," |
| 76 | + + "\"message\":\"Session expired. Please log in.\"," |
| 77 | + + "\"loginUrl\":\"" + escapedLoginUrl + "\"}"); |
| 78 | + } else { |
| 79 | + delegate.commence(request, response, authException); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + private boolean isHtmxRequest(HttpServletRequest request) { |
| 84 | + return "true".equalsIgnoreCase(request.getHeader(HX_REQUEST_HEADER)); |
| 85 | + } |
| 86 | +} |
0 commit comments