fix(604): handle HTMX authentication errors with custom entry point (#611)

This commit is contained in:
Daniel Graf
2026-01-02 09:42:55 +01:00
committed by GitHub
parent 5768d06ccd
commit 77f7270a39
2 changed files with 31 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package com.dedicatedcode.reitti.config;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class HtmxAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
// Check if the request is coming from HTMX
if ("true".equals(request.getHeader("HX-Request"))) {
// Tell HTMX to redirect the whole window to the login page
response.setHeader("HX-Redirect", "/login");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
// Standard behavior for non-HTMX requests (regular 302 redirect)
response.sendRedirect("/login");
}
}
}

View File

@@ -34,6 +34,9 @@ public class SecurityConfig {
@Autowired
private SetupFilter setupFilter;
@Autowired
private HtmxAuthenticationEntryPoint authenticationEntryPoint;
@Autowired(required = false)
private LogoutSuccessHandler oidcLogoutSuccessHandler;
@@ -77,6 +80,7 @@ public class SecurityConfig {
.rememberMeParameter("remember-me")
.useSecureCookie(false)
)
.exceptionHandling(exceptionHandling -> exceptionHandling.authenticationEntryPoint(authenticationEntryPoint))
.logout(logout -> {
if (oidcLogoutSuccessHandler != null) {
logout.logoutSuccessHandler(oidcLogoutSuccessHandler);