15

I have a Spring Boot project with keycloak integrated. Now I want to disable keycloak for testing purposes.

I tried by adding keycloak.enabled=false to application.properties as mentioned in Keycloak documentation but it didnt work.

So how do I disable it?

4
  • Do you try just remove keycloak-spring-boot-starter from dependencies section of your maven on gradle build file? Dec 18, 2017 at 5:19
  • 2
    No. I actually wanted to disable it without removing the keycloak dependency.
    – Charlie
    Dec 18, 2017 at 8:03
  • Did you solve the issue? I want to disable it in Spring Boot controller tests but solutions in this thread didn't work. Mar 26, 2019 at 21:58
  • I just posted my solution below. Please have a look.
    – Charlie
    Mar 27, 2019 at 3:06

5 Answers 5

14

Update 2022

Please follow this excellent guide on Baeldung.


For anyone who might have the same trouble, here is what I did.

I didn't disable Keycloak but I made a separate a Keycloak config file for testing purposes.

Here is my config file

@Profile("test")
@Configuration
@EnableWebSecurity
public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll();
        http.headers().frameOptions().disable();
        http.csrf().disable();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**");
    }

    @Bean
    @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public AccessToken accessToken() {
        AccessToken accessToken = new AccessToken();
        accessToken.setSubject("abc");
        accessToken.setName("Tester");

        return accessToken;

    }

}

Please note it is important to use this only in a test environment and therefore I have annotated the config as @Profile("test"). I have also added an AccessToken bean since some of the auditing features in my application depend on it.

5

It should work, but based on the last comment on the jira ticket for this, it seems it is not.

As the description state you could exclude the spring boot autoconfiguration for keycloak adding to your application.properties: spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration

2
  • 3
    It does not work if you have a also Spring Security enabled, the enable flag only works for the Spring Boot Adapter used alone. We have a ticket for supporting also the flag when Spring Secuiryt is used. Dec 18, 2017 at 16:24
  • the classname to exclude is now KeycloakAutoConfiguration as of spring boot 2.5.6 + Keycloak 16.1.0 (see my answer below)
    – Rhubarb
    Jan 15, 2022 at 19:59
3

You need to exclude keycloak auto configuration. In order to do this just add this entry to your related spring configuration file, in your case application.properties.

spring.autoconfigure.exclude = org.keycloak.adapters.springboot.KeycloakAutoConfiguration
2

My Workaround:

1. Create a Custom-Filter and add it to the (Spring) Security-Chain in early position.
2. Create a flag in the application.yml (securityEnabled)
3. Query the flag in the Custom-Filter. If 'true' simply go on with the next filter by calling chain.doFilter(). If 'false' create a dummy Keycloak-Account set the roles you need and set it to the context.
4. By the way the roles are also outsourced to the application.yml
5. Skip the rest of the filters in the Security-Chain (so no keycloak-stuff is executed and the corresponding Authorization happend)

In Detail:

1. Class of Custom-Filter

public class CustomFilter extends OncePerRequestFilter {

  @Value("${securityEnabled}")
  private boolean securityEnabled;

  @Value("${grantedRoles}")
  private String[] grantedRoles;

  @Override
  public void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
                       FilterChain chain) throws IOException, ServletException {

      if (!securityEnabled){
          // Read roles from application.yml
          Set<String> roles = Arrays.stream(grantedRoles)
                  .collect(Collectors.toCollection(HashSet::new));
          // Dummy Keycloak-Account
          RefreshableKeycloakSecurityContext session = new RefreshableKeycloakSecurityContext(null, null, null, null, null, null, null);
          final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>("Dummy_Principal", session);
          final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, principal.getKeycloakSecurityContext());
          // Dummy Security Context
          SecurityContext context = SecurityContextHolder.createEmptyContext();
          context.setAuthentication(new KeycloakAuthenticationToken(account, false));
          SecurityContextHolder.setContext(context);

          // Skip the rest of the filters
          req.getRequestDispatcher(req.getServletPath()).forward(req, res);
      }

      chain.doFilter(req, res);
  }
}


2. Insert Custom-Filter in the http-Configuration of Spring-Security

protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http
            .cors()
            .and()
            .csrf()
            .disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
            .and()
            .addFilterAfter(CustomFilter(), CsrfFilter.class)
            .authorizeRequests()
            .anyRequest().permitAll();
}

Have a look at the default Filter-Chain after configuring Keycloak:

Filter-Chain

So it´s obvious to insert the Custom-Filter at position 5 to avoid the whole Keycloak-Magic.

I have used this workaround to defeat the method security and it´s @Secured-Annotation.

4
  • So how do u enable Keycloak again? By commenting out the filter?
    – Charlie
    May 17, 2020 at 7:46
  • By setting the flag securityEnabled = true in the application.yml. Then the if-Statement in the filter is skipped.
    – Twelve
    May 17, 2020 at 11:01
  • What is the " .sessionAuthenticationStrategy(sessionAuthenticationStrategy()) "? How do you define the method sessionAuthenticationStrategy()?
    – Asu
    Aug 25, 2021 at 13:05
  • I can't get this approach to work.. my custom filter's "doFilterInternal" method is never invoked, even though the filter itself is registered at the correct place on the chain. Tried with implementing Filter directly or extending GenericFilterBean. "doFilter" is just never called...
    – Asu
    Aug 25, 2021 at 20:54
0

Updated answer for spring boot 2.5.6 and keycloak 16.1.0

Set this in your application.properties:

spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakAutoConfiguration

(The autoconfig class name has changed since earlier answers)

The keycloak adapter dependency brings in the standard spring security autoconfig too, so if you want to disable both use this:

spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakAutoConfiguration,org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.