Last updated: 2023-04-30

  1. Learn
  2. Spring Security
  3. Keycloak HTMX

Supporting OAuth with Spring Boot and HTMX

If we're using HTMX with the boost function enabled, all links are automatically converted to Ajax requests and the result is added to the DOM via JavaScript. However, this behaviour applies to redirects as well - and affects the setup of the OAuth client of our Spring Boot app.

Suppose we have connected our Spring Boot application to a Keycloak server via OAuth / OIDC, as described in this article. Now when we call a protected resource, Spring Boot will detect the lack of authentication and automatically redirect us to the Keycloak login. When our initial click was handled by HTMX, the browser will display the following error in the console.

The browser has correctly detected that the origin has changed and Keycloak is not allowing it. Therefore, the CORS (Cross-Origin Resource Sharing) error is issued in the console in the browser. However, without HTMX, the error would not have occurred - so what can we do to avoid the CORS error? To fix this, we first add our own OAuthRedirectStrategy to the application.

Creating a custom RedirectStrategy

If via the HX-Request header a HTMX request has been recognized, the response will be modified. Instead of a real redirect, the HX-Redirect header will now be returned - so rather than redirecting the Ajax request, HTMX will recognize the new header in the response and initiate a real browser redirect. With this change we fix the CORS error and at the same time ensure that the Keycloak login page will not run in the HTMX context.

Lastly, we now configure OAuth to use our new redirect strategy. Instead of .oauth2Login(withDefaults()) we write:

Adjusting our security config

The Bootify Builder includes the Security tab in the Professionel plan, where Keycloak can be enabled for the frontend. If the option for HTMX has been activated, the OAuthRedirectStrategy as well as its configuration is automatically added to the source code.

See Pricing
or read quickstart