Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

NPI – Frontegg – Security – (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Overview

Keycloak is a free and open-source identity and access management program, often used in our software stacks today. During the testing phase, it may be useful to disable its use to focus on business testing. We may also not have a Keycloak server in our test environment.

In this tutorial, we'll disable the configuration put in place by the Keycloak starter. We'll also look at modifying Spring Security when it's enabled in our project.

2. Disabling Keycloak in a Non-Spring-Security Environment

We'll start by looking at how to disable Keycloak in an application that doesn't use Spring Security.

2.1. Application Setup

Let's start by adding the keycloak-spring-boot-starter dependency to our project:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>

Additionally, we need to add the dependencies of the various embedded containers brought by the keycloak-adapter-bom dependency:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.keycloak.bom</groupId>
            <artifactId>keycloak-adapter-bom</artifactId>
            <version>15.0.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Next, we'll add to our application.properties the configuration for our Keycloak server:

keycloak.auth-server-url=http://localhost:8180/auth
keycloak.realm=SpringBootKeycloak
keycloak.resource=login-app
keycloak.public-client=true
keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/users/*

This configuration ensures that requests to the /users URL will only be accessible to authenticated users with the user role.

Finally, let's add a UserController that retrieves a User:

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{userId}")
    public User getCustomer(@PathVariable Long userId) {
        return new User(userId, "John", "Doe");
    }
}

2.2. Disabling Keycloak

Now that our application is in place, let's write a simple test to get a user:

@Test
public void givenUnauthenticated_whenGettingUser_shouldReturnUser() {
    ResponseEntity<User> responseEntity = restTemplate.getForEntity("/users/1", User.class);

    assertEquals(HttpStatus.SC_OK, responseEntity.getStatusCodeValue());
    assertNotNull(responseEntity.getBody()
        .getFirstname());
}

This test will fail because we didn't provide any authentication to restTemplate, or because the Keycloak server is not available.

The Keycloak adapter implements the Spring autoconfiguration of Keycloak security. Autoconfigurations rely on the presence of a class in the classpath or on the value of a property. Specifically, the @ConditionalOnProperty annotation is very handy for this particular need.

To disable Keycloak security, we need to inform the adapter that it should not load the corresponding configuration. We can do this by assigning the property as follows:

keycloak.enabled=false

If we launch our test again, it will now succeed without any authentication involved.

3. Disabling Keycloak in a Spring Security Environment

We often use Keycloak in combination with Spring Security. In this case, it's not enough to disable the Keycloak configuration, but we also need to modify the Spring Security configuration to allow anonymous requests to reach the controllers.

3.1. Application Setup

Let's start by adding the spring-boot-starter-security dependency to our project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Next, we implement the WebSecurityConfigurerAdapter to define the configuration needed for Spring Security. The Keycloak adapter provides an abstract class and annotation that for this purpose:

@KeycloakConfiguration
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated();
    }
}

Here, we're configuring Spring Security to allow requests from authenticated users only.

3.2. Disabling Keycloak

As well as disabling Keycloak like we did earlier, we now also need to disable Spring Security.

We could use profiles to tell Spring whether or not to activate the Keycloak configuration during our tests:

@KeycloakConfiguration
@Profile("tests")
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    // ...
}

However, a more elegant way is to reuse the keycloak.enable property, similar to the Keycloak adapter:

@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    // ...
}

As a result, Spring only enables Keycloak configuration if the keycloak.enable property is true. In case the property is missing, matchIfMissing enables it by default.

As we're using the Spring Security starter, it's not enough to disable our Spring Security configuration. Indeed, following Spring's opinionated defaults configuration principles, the starter will create a default security layer.

Let's create a configuration class to disable it:

@Configuration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "false")
public class DisableSecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .permitAll();
       return http.build();
    }
}

We're still using our keycloak.enable property, but this time Spring enables the configuration if its value is set to false.

4. Conclusion

In this article, we looked at how to disable Keycloak security in a Spring environment, with or without Spring Security.

As usual, all the code samples used in this article can be found over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Security footer banner
Comments are closed on this article!