forked from dasniko/testcontainers-keycloak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeycloakContainerExtensionTest.java
176 lines (150 loc) · 7.74 KB
/
KeycloakContainerExtensionTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package dasniko.testcontainers.keycloak;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import dasniko.testcontainers.keycloak.extensions.oidcmapper.TestOidcProtocolMapper;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.jupiter.api.Test;
import org.keycloak.TokenVerifier;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static dasniko.testcontainers.keycloak.KeycloakContainerTest.TEST_REALM_JSON;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
public class KeycloakContainerExtensionTest {
@Test
public void shouldStartKeycloakWithNonExistingExtensionClassFolder() {
try (KeycloakContainer keycloak = new KeycloakContainer()
.withProviderClassesFrom("target/does_not_exist")) {
keycloak.start();
}
}
/**
* Deploys the Keycloak extensions from the test-classes folder into the created Keycloak container.
*/
@Test
public void shouldDeployProvider() throws Exception {
try (KeycloakContainer keycloak = new KeycloakContainer()
// this would normally be just "target/classes"
.withProviderClassesFrom("target/test-classes")
.withRealmImportFile(TEST_REALM_JSON)) {
keycloak.start();
configureCustomOidcProtocolMapper(keycloak);
Keycloak keycloakClient = keycloak.getKeycloakAdminClient();
AccessTokenResponse tokenResponse = keycloakClient.tokenManager().getAccessToken();
// parse the received access-token
TokenVerifier<AccessToken> verifier = TokenVerifier.create(tokenResponse.getToken(), AccessToken.class);
verifier.parse();
// check for the custom claim
AccessToken accessToken = verifier.getToken();
String customClaimValue = (String)accessToken.getOtherClaims().get(TestOidcProtocolMapper.CUSTOM_CLAIM_NAME);
System.out.printf("Custom Claim name %s=%s%n", TestOidcProtocolMapper.CUSTOM_CLAIM_NAME, customClaimValue);
assertThat(customClaimValue, notNullValue());
assertThat(customClaimValue, startsWith("testdata:"));
}
}
@Test
public void shouldDeployProviderAndCallCustomEndpoint() throws Exception {
try (KeycloakContainer keycloak = new KeycloakContainer()
// this would normally be just "target/classes"
.withProviderClassesFrom("target/test-classes")) {
keycloak.start();
ObjectMapper objectMapper = new ObjectMapper();
String uri = keycloak.getAuthServerUrl() + "/realms/master/test-resource/hello";
// test the "public" endpoint
Map<String, String> result = objectMapper.readValue(new URL(uri), new TypeReference<>() {});
assertThat(result.get("hello"), is("master"));
// and now the secured endpoint, first we need a valid token
Keycloak keycloakClient = keycloak.getKeycloakAdminClient();
AccessTokenResponse accessTokenResponse = keycloakClient.tokenManager().getAccessToken();
URL url = new URL(keycloak.getAuthServerUrl() + "/realms/master/test-resource/hello-auth");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + accessTokenResponse.getToken());
Map<String, String> authResult = objectMapper.readValue(conn.getInputStream(), new TypeReference<>() {});
assertThat(authResult.get("hello"), is("admin"));
}
}
@Test
public void shouldDeployProviderWithDependencyAndCallCustomEndpoint() throws Exception {
List<File> dependencies = Maven.resolver()
.loadPomFromFile("./pom.xml")
.resolve("net.datafaker:datafaker")
.withoutTransitivity().asList(File.class);
try (KeycloakContainer keycloak = new KeycloakContainer()
.withProviderClassesFrom("target/test-classes")
.withProviderLibsFrom(dependencies)) {
keycloak.start();
ObjectMapper objectMapper = new ObjectMapper();
String uri = keycloak.getAuthServerUrl() + "/realms/master/yoda/quote";
Map<String, String> result = objectMapper.readValue(new URL(uri), new TypeReference<>() {});
String quote = result.get("yoda");
assertThat(quote, not(emptyOrNullString()));
System.out.printf("Yoda says: %s\n", quote);
}
}
@Test
public void shouldCacheStaticContentPerDefault() {
try (KeycloakContainer keycloak = new KeycloakContainer()
.withProviderClassesFrom("target/test-classes")) {
keycloak.start();
given().when().get(getProjectLogoUrl(keycloak))
.then().statusCode(200).header("Cache-Control", containsString("max-age=2592000"));
}
}
@Test
public void shouldNotCacheStaticContentWithDisabledCaching() {
try (KeycloakContainer keycloak = new KeycloakContainer()
.withProviderClassesFrom("target/test-classes")
.withDisabledCaching()) {
keycloak.start();
given().when().get(getProjectLogoUrl(keycloak))
.then().statusCode(200).header("Cache-Control", "no-cache");
}
}
private String getProjectLogoUrl(KeycloakContainer keycloak) {
ObjectMapper objectMapper = new ObjectMapper();
String uri = keycloak.getAuthServerUrl() + "/realms/master/test-resource/theme-root";
try {
Map<String, String> themeRoot = objectMapper.readValue(new URL(uri), new TypeReference<>(){});
return themeRoot.get("url") + "/login/keycloak.v2/img/keycloak-logo-text.png";
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Configures the {@link TestOidcProtocolMapper} to the given client in the given realm.
*/
static void configureCustomOidcProtocolMapper(KeycloakContainer keycloak) {
keycloak.disableLightweightAccessTokenForAdminCliClient(KeycloakContainer.MASTER_REALM);
ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation();
mapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
mapper.setProtocolMapper(TestOidcProtocolMapper.ID);
mapper.setName("test-mapper");
Map<String, String> config = new HashMap<>();
config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
mapper.setConfig(config);
RealmResource realm = keycloak.getKeycloakAdminClient().realm(KeycloakContainer.MASTER_REALM);
ClientRepresentation client = realm.clients().findByClientId(KeycloakContainer.ADMIN_CLI_CLIENT).get(0);
realm.clients().get(client.getId()).getProtocolMappers().createMapper(mapper).close();
}
}