BAEL-5589-springboot-keycloak-integration-testing-with-testcontainers (#12484)

This commit is contained in:
Christian German 2022-07-15 17:34:13 +02:00 committed by GitHub
parent 18f919bf30
commit b8dc7b574a
11 changed files with 2102 additions and 8 deletions

View File

@ -23,6 +23,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId> <artifactId>spring-boot-starter-web-services</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
@ -43,13 +47,39 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testcontainers</groupId> <groupId>org.keycloak</groupId>
<artifactId>testcontainers</artifactId> <artifactId>keycloak-spring-boot-starter</artifactId>
<version>1.17.2</version> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.github.dasniko</groupId>
<artifactId>testcontainers-keycloak</artifactId>
<version>${testcontainers-keycloak.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontainers.version}</version>
</dependency>
</dependencies> </dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>${keycloak-adapter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -77,6 +107,9 @@
<properties> <properties>
<start-class>com.baeldung.boot.Application</start-class> <start-class>com.baeldung.boot.Application</start-class>
<testcontainers.version>1.17.2</testcontainers.version>
<testcontainers-keycloak.version>1.10.0</testcontainers-keycloak.version>
<keycloak-adapter.version>13.0.1</keycloak-adapter.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,12 @@
package com.baeldung.keycloaktestcontainers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.keycloaktestcontainers.configuration;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeycloakConfiguration {
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.keycloaktestcontainers.configuration;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public class KeycloakSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
/**
* {@inheritDoc}
*/
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
/**
* {@inheritDoc}
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf()
.disable()
.cors()
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.keycloaktestcontainers.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.keycloaktestcontainers.dto.UserDto;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("me")
public UserDto getMe() {
return new UserDto(1L, "janedoe", "Doe", "Jane", "jane.doe@baeldung.com");
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.keycloaktestcontainers.dto;
public class UserDto {
private long id;
private String username;
private String lastname;
private String firstname;
private String email;
public UserDto(long id, String username, String lastname, String firstname, String email) {
this.id = id;
this.username = username;
this.lastname = lastname;
this.firstname = firstname;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@ -1 +1,4 @@
keycloak.enabled=true
keycloak.realm=baeldung
keycloak.resource=baeldung-api
keycloak.auth-server-url=http://localhost:8081

View File

@ -0,0 +1,85 @@
package com.baeldung.keycloaktestcontainers;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import javax.annotation.PostConstruct;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import dasniko.testcontainers.keycloak.KeycloakContainer;
import io.restassured.RestAssured;
@ContextConfiguration(initializers = { IntegrationTest.Initializer.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class IntegrationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationTest.class.getName());
@LocalServerPort
private int port;
static final KeycloakContainer keycloak = new KeycloakContainer().withRealmImportFile("keycloak/realm-export.json");
@PostConstruct
public void init() {
RestAssured.baseURI = "http://localhost:" + port;
}
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
keycloak.start();
TestPropertyValues.of("keycloak.auth-server-url=" + keycloak.getAuthServerUrl())
.applyTo(configurableApplicationContext.getEnvironment());
}
}
protected String getJaneDoeBearer() {
try {
URI authorizationURI = new URIBuilder(keycloak.getAuthServerUrl() + "/realms/baeldung/protocol/openid-connect/token").build();
WebClient webclient = WebClient.builder()
.build();
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.put("grant_type", Collections.singletonList("password"));
formData.put("client_id", Collections.singletonList("baeldung-api"));
formData.put("username", Collections.singletonList("jane.doe@baeldung.com"));
formData.put("password", Collections.singletonList("s3cr3t"));
String result = webclient.post()
.uri(authorizationURI)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.retrieve()
.bodyToMono(String.class)
.block();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return "Bearer " + jsonParser.parseMap(result)
.get("access_token")
.toString();
} catch (URISyntaxException e) {
LOGGER.error("Can't obtain an access token from Keycloak!", e);
}
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.keycloaktestcontainers;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
class UserControllerIntegrationTest extends IntegrationTest {
@Test
void givenAuthenticatedUser_whenGetMe_shouldReturnMyInfo() {
given().header("Authorization", getJaneDoeBearer())
.when()
.get("/users/me")
.then()
.body("username", equalTo("janedoe"))
.body("lastname", equalTo("Doe"))
.body("firstname", equalTo("Jane"))
.body("email", equalTo("jane.doe@baeldung.com"));
}
}

View File

@ -1,3 +1,4 @@
# logging.level.com.baeldung.testloglevel=DEBUG keycloak.enabled=true
keycloak.realm=baeldung
# logging.level.root=INFO keycloak.resource=baeldung-api
keycloak.auth-server-url=http://localhost:8081