Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,38 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
}
```

In addition, htmx provides a special way to send a redirect instruction to the client, keeping a success code ([200](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200)) and sending a custom HTTP header from the server ([HX-Location](https://htmx.org/headers/hx-location/) / [HX-Redirect](https://htmx.org/headers/hx-redirect/)). Htmx correctly interprets these headers and follows the redirect, replacing the response in the page body.

You can take advantage of this behavior by integrating the `HxLocationRedirectAuthenticationFailureHandler`, `HxLocationRedirectAuthenticationSuccessHandler`, `HxLocationRedirectLogoutSuccessHandler`, `HxLocationRedirectAuthenticationEntryPoint` and/or `HxLocationRedirectAccessDeniedHandler` into the `SecurityFilterChain` bean definition.

```java
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// probably some other configurations here
return http
.formLogin(login -> login
.failureHandler(new HxLocationRedirectAuthenticationFailureHandler("/login?failure"))
.successHandler(new HxLocationRedirectAuthenticationSuccessHandler("/home?login"))
).logout(logout -> logout
.logoutSuccessHandler(new HxLocationRedirectLogoutSuccessHandler("/home?logout"))
).exceptionHandling(handler -> handler
.authenticationEntryPoint(new HxLocationRedirectAuthenticationEntryPoint("/login?unauthorized"))
.accessDeniedHandler(new HxLocationRedirectAccessDeniedHandler("/error?forbidden"))
).build();
}
```

Also, you can use the provided `HxLocationBoostedRedirectStrategy` as the second parameter in the handlers, instructing the client to include the [HX-Boosted](https://htmx.org/reference/#headers) header in the new request. This can be useful if you want to take advantage of existing controller optimizations, for example, rendering a fragment instead of the full page for non-boosted, htmx-driven requests:

```java
@GetMapping("/login")
String login(HtmxRequest request) {
return request.isHtmxRequest() && !request.isBoosted()
? "pages/login :: content"
: "pages/login";
}
```

### Thymeleaf

#### Markup Selectors and HTML Fragments
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import io.github.wimdeblauwe.htmx.spring.boot.mvc.HtmxLocation;
import io.github.wimdeblauwe.htmx.spring.boot.mvc.HtmxResponseHeader;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import tools.jackson.databind.json.JsonMapper;

import java.io.IOException;
import java.util.Map;

import static io.github.wimdeblauwe.htmx.spring.boot.mvc.HtmxRequestHeader.HX_BOOSTED;
import static org.springframework.http.HttpStatus.OK;

/**
* htmx-friendly redirect strategy to be used with any security handler that performs redirects.
* <p>
* When instantiated by the default constructor, it checks for htmx requests and responds with {@link HttpStatus#OK},
* including the target URL in the {@link HtmxResponseHeader#HX_LOCATION} header.
* <p>
* It also sets the {@code headers} and {@code target} parameters, instructing the client to include the
* {@code HX-Boosted} header in the new request, and to swap the response into the {@code body} element.
* <p>
* Example:
* <pre> {@code
* HX-Location: {
* "path":"/login?unauthorized",
* "headers":{"HX-Boosted":"true"},
* "target":"body"
* }
* } </pre>
* <p>
* These parameters are useful if you want to take advantage of existing controller optimizations, to render a fragment
* instead of the full page for non-boosted, htmx-driven requests:
* <p>
* <pre> {@code
* @GetMapping("/login")
* String login(HtmxRequest request) {
* return request.isHtmxRequest() && !request.isBoosted()
* ? "pages/login :: content"
* : "pages/login";
* }
* } </pre>
* <p>
* In case you don’t need this "boosted" behavior, use the {@link HxLocationRedirectStrategy} instead.
* <p>
* For non-htmx requests, it delegates to the {@link DefaultRedirectStrategy}.
*
* @author LC Nicolau
* @see <a href="https://htmx.org/headers/hx-location/">HX-Location Response Header</a>
* @see <a href="https://htmx.org/reference/#headers">HTTP Header Reference</a>
* @since 5.0.0
*/
public class HxLocationBoostedRedirectStrategy extends HxLocationRedirectStrategy {

private final JsonMapper jsonMapper;

public HxLocationBoostedRedirectStrategy() {
this(OK);
}

public HxLocationBoostedRedirectStrategy(HttpStatus status) {
super(status);
this.jsonMapper = new JsonMapper();
}

@Override
protected void sendHxLocationRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
super.sendHxLocationRedirect(request, response, boosted(url));
}

protected String boosted(String url) {
HtmxLocation location = new HtmxLocation(url);
location.setTarget("body");
location.setHeaders(Map.of(HX_BOOSTED.getValue(), "true"));
return jsonMapper.writeValueAsString(location);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

/**
* Handles navigation on {@link HttpStatus#FORBIDDEN} access by delegating to the {@link HxLocationRedirectStrategy},
* providing an htmx-friendly redirect mechanism.
* <p>
* This class is not used by the library itself, but users of the library can use it to configure their security for
* native htmx redirects.
*
* @author LC Nicolau
* @since 5.0.0
*/
public class HxLocationRedirectAccessDeniedHandler implements AccessDeniedHandler {

private final String redirectUrl;
private final RedirectStrategy redirectStrategy;

public HxLocationRedirectAccessDeniedHandler(String redirectUrl) {
this(redirectUrl, new HxLocationRedirectStrategy(HttpStatus.FORBIDDEN));
}

public HxLocationRedirectAccessDeniedHandler(String redirectUrl, RedirectStrategy redirectStrategy) {
this.redirectUrl = redirectUrl;
this.redirectStrategy = redirectStrategy;
}

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
redirectStrategy.sendRedirect(request, response, redirectUrl);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.RedirectStrategy;

import java.io.IOException;

/**
* Handles navigation on {@link HttpStatus#UNAUTHORIZED} access by delegating to the {@link HxLocationRedirectStrategy},
* providing an htmx-friendly redirect mechanism.
* <p>
* This class is not used by the library itself, but users of the library can use it to configure their security for
* native htmx redirects.
*
* @author LC Nicolau
* @since 5.0.0
*/
public class HxLocationRedirectAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final String redirectUrl;
private final RedirectStrategy redirectStrategy;

public HxLocationRedirectAuthenticationEntryPoint(String redirectUrl) {
this(redirectUrl, new HxLocationRedirectStrategy(HttpStatus.UNAUTHORIZED));
}

public HxLocationRedirectAuthenticationEntryPoint(String redirectUrl, RedirectStrategy redirectStrategy) {
this.redirectUrl = redirectUrl;
this.redirectStrategy = redirectStrategy;
}

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
redirectStrategy.sendRedirect(request, response, redirectUrl);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import java.io.IOException;

/**
* Handles a failed authentication attempt by delegating to the {@link SimpleUrlAuthenticationFailureHandler}, using
* {@link HxLocationRedirectStrategy} to provide an htmx-friendly redirect mechanism.
* <p>
* This class is not used by the library itself, but users of the library can use it to configure their security for
* native htmx redirects.
*
* @author LC Nicolau
* @since 5.0.0
*/
public class HxLocationRedirectAuthenticationFailureHandler implements AuthenticationFailureHandler {

private final AuthenticationFailureHandler delegate;

public HxLocationRedirectAuthenticationFailureHandler(String defaultFailureUrl) {
this(defaultFailureUrl, new HxLocationRedirectStrategy(HttpStatus.UNAUTHORIZED));
}

public HxLocationRedirectAuthenticationFailureHandler(String defaultFailureUrl, RedirectStrategy redirectStrategy) {
var handler = new SimpleUrlAuthenticationFailureHandler();
handler.setDefaultFailureUrl(defaultFailureUrl);
handler.setRedirectStrategy(redirectStrategy);
this.delegate = handler;
}

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
delegate.onAuthenticationFailure(request, response, exception);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import java.io.IOException;

/**
* Handles post-authentication navigation by delegating to the {@link SavedRequestAwareAuthenticationSuccessHandler},
* using {@link HxLocationRedirectStrategy} to provide an htmx-friendly redirect mechanism.
* <p>
* This class is not used by the library itself, but users of the library can use it to configure their security for
* native htmx redirects.
*
* @author LC Nicolau
* @since 5.0.0
*/
public class HxLocationRedirectAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

private final AuthenticationSuccessHandler delegate;

public HxLocationRedirectAuthenticationSuccessHandler(String defaultSuccessUrl) {
this(defaultSuccessUrl, false);
}

public HxLocationRedirectAuthenticationSuccessHandler(String defaultSuccessUrl, boolean alwaysUse) {
this(defaultSuccessUrl, alwaysUse, new HxLocationRedirectStrategy());
}

public HxLocationRedirectAuthenticationSuccessHandler(String defaultSuccessUrl, RedirectStrategy redirectStrategy) {
this(defaultSuccessUrl, false, redirectStrategy);
}

public HxLocationRedirectAuthenticationSuccessHandler(String defaultSuccessUrl, boolean alwaysUse, RedirectStrategy redirectStrategy) {
var handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setDefaultTargetUrl(defaultSuccessUrl);
handler.setAlwaysUseDefaultTargetUrl(alwaysUse);
handler.setRedirectStrategy(redirectStrategy);
this.delegate = handler;
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
delegate.onAuthenticationSuccess(request, response, authentication);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package io.github.wimdeblauwe.htmx.spring.boot.security;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import java.io.IOException;

/**
* Handles post-logout navigation by delegating to the {@link SimpleUrlLogoutSuccessHandler}, using
* {@link HxLocationRedirectStrategy} to provide an htmx-friendly redirect mechanism.
* <p>
* This class is not used by the library itself, but users of the library can use it to configure their security for
* native htmx redirects.
*
* @author LC Nicolau
* @since 5.0.0
*/
public class HxLocationRedirectLogoutSuccessHandler implements LogoutSuccessHandler {

private final LogoutSuccessHandler delegate;

public HxLocationRedirectLogoutSuccessHandler(String logoutSuccessUrl) {
this(logoutSuccessUrl, false);
}

public HxLocationRedirectLogoutSuccessHandler(String logoutSuccessUrl, boolean alwaysUse) {
this(logoutSuccessUrl, alwaysUse, new HxLocationRedirectStrategy());
}

public HxLocationRedirectLogoutSuccessHandler(String logoutSuccessUrl, RedirectStrategy redirectStrategy) {
this(logoutSuccessUrl, false, redirectStrategy);
}

public HxLocationRedirectLogoutSuccessHandler(String logoutSuccessUrl, boolean alwaysUse, RedirectStrategy redirectStrategy) {
var handler = new SimpleUrlLogoutSuccessHandler();
handler.setDefaultTargetUrl(logoutSuccessUrl);
handler.setAlwaysUseDefaultTargetUrl(alwaysUse);
handler.setRedirectStrategy(redirectStrategy);
this.delegate = handler;
}

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
delegate.onLogoutSuccess(request, response, authentication);
}

}
Loading