KEYCLOAK-7137 Polish testsuite a bit

This commit is contained in:
vramik 2018-04-12 13:54:04 +02:00 committed by Hynek Mlnařík
parent 095fec95e5
commit 9a94004fc9
36 changed files with 166 additions and 263 deletions

View file

@ -68,7 +68,7 @@ public class ActionURIUtils {
public static String removeQueryParamFromURI(String actionURI, String paramName) { public static String removeQueryParamFromURI(String actionURI, String paramName) {
return UriBuilder.fromUri(actionURI) return UriBuilder.fromUri(actionURI)
.replaceQueryParam(paramName, null) .replaceQueryParam(paramName, (Object[]) null)
.build().toString(); .build().toString();
} }

View file

@ -46,7 +46,7 @@ public class ProfileAssume {
ProfileInfoRepresentation profileInfo = adminClient.serverInfo().getInfo().getProfileInfo(); ProfileInfoRepresentation profileInfo = adminClient.serverInfo().getInfo().getProfileInfo();
profile = profileInfo.getName(); profile = profileInfo.getName();
List<String> disabled = profileInfo.getDisabledFeatures(); List<String> disabled = profileInfo.getDisabledFeatures();
disabledFeatures = Collections.unmodifiableSet(new HashSet(disabled)); disabledFeatures = Collections.unmodifiableSet(new HashSet<>(disabled));
adminClient.close(); adminClient.close();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to obtain profile / features info from serverinfo endpoint of " + authServerContextRoot, e); throw new RuntimeException("Failed to obtain profile / features info from serverinfo endpoint of " + authServerContextRoot, e);

View file

@ -22,8 +22,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.ws.rs.NotFoundException;
import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.client.KeycloakTestingClient; import org.keycloak.testsuite.client.KeycloakTestingClient;
@ -44,7 +42,7 @@ public final class TestContext {
private boolean adminLoggedIn; private boolean adminLoggedIn;
private final Map customContext = new HashMap<>(); private final Map<Object, Object> customContext = new HashMap<>();
private Keycloak adminClient; private Keycloak adminClient;
private KeycloakTestingClient testingClient; private KeycloakTestingClient testingClient;
@ -55,7 +53,7 @@ public final class TestContext {
private boolean initialized; private boolean initialized;
// Key is realmName, value are objects to clean after the test method // Key is realmName, value are objects to clean after the test method
private Map<String, TestCleanup> cleanups = new ConcurrentHashMap<>(); private final Map<String, TestCleanup> cleanups = new ConcurrentHashMap<>();
public TestContext(SuiteContext suiteContext, Class testClass) { public TestContext(SuiteContext suiteContext, Class testClass) {
this.suiteContext = suiteContext; this.suiteContext = suiteContext;

View file

@ -57,7 +57,7 @@ public class Registry implements ContainerRegistry {
private final List<Container> containers; private final List<Container> containers;
private Injector injector; private final Injector injector;
private static final Logger logger = Logger.getLogger(RegistryCreator.class.getName()); private static final Logger logger = Logger.getLogger(RegistryCreator.class.getName());
@ -98,7 +98,7 @@ public class Registry implements ContainerRegistry {
return addContainer(injector.inject( return addContainer(injector.inject(
new ContainerImpl(definition.getContainerName(), dcService, definition))); new ContainerImpl(definition.getContainerName(), dcService, definition)));
} catch (Exception e) { } catch (ConfigurationException e) {
throw new ContainerCreationException("Could not create Container " + definition.getContainerName(), e); throw new ContainerCreationException("Could not create Container " + definition.getContainerName(), e);
} }
} }

View file

@ -20,9 +20,9 @@ package org.keycloak.testsuite.arquillian.migration;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.nio.charset.Charset;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
@ -41,20 +41,14 @@ public class MigrationContext {
String file = getOfflineTokenLocation(); String file = getOfflineTokenLocation();
logger.infof("Reading previously saved offline token from the file: %s", file); logger.infof("Reading previously saved offline token from the file: %s", file);
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(file)) {
try { String offlineToken = StreamUtil.readString(fis, Charset.forName("UTF-8"));
fis = new FileInputStream(file);
String offlineToken = StreamUtil.readString(fis);
File f = new File(file); File f = new File(file);
f.delete(); f.delete();
logger.infof("Deleted file with offline token: %s", file); logger.infof("Deleted file with offline token: %s", file);
return offlineToken; return offlineToken;
} finally {
if (fis != null) {
fis.close();
}
} }
} }
@ -85,14 +79,8 @@ public class MigrationContext {
String file = getOfflineTokenLocation(); String file = getOfflineTokenLocation();
logger.infof("Saving offline token to file: %s", file); logger.infof("Saving offline token to file: %s", file);
PrintWriter writer = null; try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
writer.print(offlineToken); writer.print(offlineToken);
} finally {
if (writer != null) {
writer.close();
}
} }
} }

View file

@ -44,9 +44,9 @@ public class Sessions extends AccountManagement {
} }
public List<List<String>> getSessions() { public List<List<String>> getSessions() {
List<List<String>> table = new LinkedList<List<String>>(); List<List<String>> table = new LinkedList<>();
for (WebElement r : driver.findElements(By.tagName("tr"))) { for (WebElement r : driver.findElements(By.tagName("tr"))) {
List<String> row = new LinkedList<String>(); List<String> row = new LinkedList<>();
for (WebElement col : r.findElements(By.tagName("td"))) { for (WebElement col : r.findElements(By.tagName("td"))) {
row.add(col.getText()); row.add(col.getText());
} }

View file

@ -35,7 +35,7 @@ public class LogChecker {
public static void checkServerLog(File logFile) throws IOException { public static void checkServerLog(File logFile) throws IOException {
log.info(String.format("Checking server log: '%s'", logFile.getAbsolutePath())); log.info(String.format("Checking server log: '%s'", logFile.getAbsolutePath()));
String[] logContent = FileUtils.readFileToString(logFile).split("\n"); String[] logContent = FileUtils.readFileToString(logFile, "UTF-8").split("\n");
for (String logText : logContent) { for (String logText : logContent) {
boolean containsError = logText.contains("ERROR") || logText.contains("SEVERE") || logText.contains("Exception "); boolean containsError = logText.contains("ERROR") || logText.contains("SEVERE") || logText.contains("Exception ");

View file

@ -115,7 +115,7 @@ public class Matchers {
* @return * @return
*/ */
public static <T> Matcher<Response> header(Matcher<Map<String, T>> matcher) { public static <T> Matcher<Response> header(Matcher<Map<String, T>> matcher) {
return new ResponseHeaderMatcher(matcher); return new ResponseHeaderMatcher<>(matcher);
} }
/** /**

View file

@ -27,13 +27,12 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert; import org.junit.Assert;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
import org.keycloak.RSATokenVerifier; import org.keycloak.RSATokenVerifier;
import org.keycloak.adapters.HttpClientBuilder;
import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.Keycloak;
import org.keycloak.common.VerificationException; import org.keycloak.common.VerificationException;
import org.keycloak.common.util.KeystoreUtil; import org.keycloak.common.util.KeystoreUtil;
@ -41,6 +40,7 @@ import org.keycloak.common.util.PemUtils;
import org.keycloak.constants.AdapterConstants; import org.keycloak.constants.AdapterConstants;
import org.keycloak.jose.jwk.JSONWebKeySet; import org.keycloak.jose.jwk.JSONWebKeySet;
import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.jose.jws.crypto.RSAProvider; import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.OIDCLoginProtocol;
@ -68,7 +68,11 @@ import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.*; import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.keycloak.testsuite.admin.Users.getPasswordOf; import static org.keycloak.testsuite.admin.Users.getPasswordOf;
@ -255,13 +259,13 @@ public class OAuthClient {
} catch(Exception e) { } catch(Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return (DefaultHttpClient)new HttpClientBuilder() return (CloseableHttpClient) new org.keycloak.adapters.HttpClientBuilder()
.keyStore(keystore, keyStorePassword) .keyStore(keystore, keyStorePassword)
.trustStore(truststore) .trustStore(truststore)
.hostnameVerification(HttpClientBuilder.HostnameVerificationPolicy.ANY) .hostnameVerification(org.keycloak.adapters.HttpClientBuilder.HostnameVerificationPolicy.ANY)
.build(); .build();
} }
return new DefaultHttpClient(); return HttpClientBuilder.create().build();
} }
public CloseableHttpResponse doPreflightRequest() { public CloseableHttpResponse doPreflightRequest() {
@ -279,7 +283,7 @@ public class OAuthClient {
try (CloseableHttpClient client = newCloseableHttpClient()) { try (CloseableHttpClient client = newCloseableHttpClient()) {
HttpPost post = new HttpPost(getAccessTokenUrl()); HttpPost post = new HttpPost(getAccessTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
if (origin != null) { if (origin != null) {
@ -333,7 +337,7 @@ public class OAuthClient {
} }
public String introspectTokenWithClientCredential(String clientId, String clientSecret, String tokenType, String tokenToIntrospect) { public String introspectTokenWithClientCredential(String clientId, String clientSecret, String tokenType, String tokenToIntrospect) {
try (CloseableHttpClient client = new DefaultHttpClient()) { try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost post = new HttpPost(getTokenIntrospectionUrl()); HttpPost post = new HttpPost(getTokenIntrospectionUrl());
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret); String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
@ -377,11 +381,10 @@ public class OAuthClient {
public AccessTokenResponse doGrantAccessTokenRequest(String realm, String username, String password, String totp, public AccessTokenResponse doGrantAccessTokenRequest(String realm, String username, String password, String totp,
String clientId, String clientSecret) throws Exception { String clientId, String clientSecret) throws Exception {
CloseableHttpClient client = newCloseableHttpClient(); try (CloseableHttpClient client = newCloseableHttpClient()) {
try {
HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm)); HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm));
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
parameters.add(new BasicNameValuePair("username", username)); parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password)); parameters.add(new BasicNameValuePair("password", password));
@ -419,18 +422,15 @@ public class OAuthClient {
post.setEntity(formEntity); post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post)); return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
} }
} }
public AccessTokenResponse doTokenExchange(String realm, String token, String targetAudience, public AccessTokenResponse doTokenExchange(String realm, String token, String targetAudience,
String clientId, String clientSecret) throws Exception { String clientId, String clientSecret) throws Exception {
CloseableHttpClient client = newCloseableHttpClient(); try (CloseableHttpClient client = newCloseableHttpClient()) {
try {
HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm)); HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm));
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE));
parameters.add(new BasicNameValuePair(OAuth2Constants.SUBJECT_TOKEN, token)); parameters.add(new BasicNameValuePair(OAuth2Constants.SUBJECT_TOKEN, token));
parameters.add(new BasicNameValuePair(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)); parameters.add(new BasicNameValuePair(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE));
@ -463,17 +463,14 @@ public class OAuthClient {
post.setEntity(formEntity); post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post)); return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
} }
} }
public AccessTokenResponse doTokenExchange(String realm, String clientId, String clientSecret, Map<String, String> params) throws Exception { public AccessTokenResponse doTokenExchange(String realm, String clientId, String clientSecret, Map<String, String> params) throws Exception {
CloseableHttpClient client = newCloseableHttpClient(); try (CloseableHttpClient client = newCloseableHttpClient()) {
try {
HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm)); HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm));
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE));
for (Map.Entry<String, String> entry : params.entrySet()) { for (Map.Entry<String, String> entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
@ -497,32 +494,26 @@ public class OAuthClient {
post.setEntity(formEntity); post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post)); return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
} }
} }
public JSONWebKeySet doCertsRequest(String realm) throws Exception { public JSONWebKeySet doCertsRequest(String realm) throws Exception {
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpGet get = new HttpGet(getCertsUrl(realm)); HttpGet get = new HttpGet(getCertsUrl(realm));
CloseableHttpResponse response = client.execute(get); CloseableHttpResponse response = client.execute(get);
return JsonSerialization.readValue(response.getEntity().getContent(), JSONWebKeySet.class); return JsonSerialization.readValue(response.getEntity().getContent(), JSONWebKeySet.class);
} finally {
closeClient(client);
} }
} }
public AccessTokenResponse doClientCredentialsGrantAccessTokenRequest(String clientSecret) throws Exception { public AccessTokenResponse doClientCredentialsGrantAccessTokenRequest(String clientSecret) throws Exception {
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(getServiceAccountUrl()); HttpPost post = new HttpPost(getServiceAccountUrl());
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret); String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
post.setHeader("Authorization", authorization); post.setHeader("Authorization", authorization);
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
if (scope != null) { if (scope != null) {
@ -538,18 +529,15 @@ public class OAuthClient {
post.setEntity(formEntity); post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post)); return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
} }
} }
public CloseableHttpResponse doLogout(String refreshToken, String clientSecret) throws IOException { public CloseableHttpResponse doLogout(String refreshToken, String clientSecret) throws IOException {
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(getLogoutUrl().build()); HttpPost post = new HttpPost(getLogoutUrl().build());
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
if (refreshToken != null) { if (refreshToken != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken)); parameters.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
} }
@ -569,17 +557,14 @@ public class OAuthClient {
post.setEntity(formEntity); post.setEntity(formEntity);
return client.execute(post); return client.execute(post);
} finally {
closeClient(client);
} }
} }
public AccessTokenResponse doRefreshTokenRequest(String refreshToken, String password) { public AccessTokenResponse doRefreshTokenRequest(String refreshToken, String password) {
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(getRefreshTokenUrl()); HttpPost post = new HttpPost(getRefreshTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN));
if (origin != null) { if (origin != null) {
@ -615,8 +600,8 @@ public class OAuthClient {
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e); throw new RuntimeException("Failed to retrieve access token", e);
} }
} finally { } catch (IOException ex) {
closeClient(client); throw new RuntimeException(ex);
} }
} }
@ -653,7 +638,7 @@ public class OAuthClient {
throw new RuntimeException("Invalid refresh token"); throw new RuntimeException("Invalid refresh token");
} }
return jws.readJsonContent(RefreshToken.class); return jws.readJsonContent(RefreshToken.class);
} catch (Exception e) { } catch (RuntimeException | JWSInputException e) {
throw new RuntimeException("Invalid refresh token", e); throw new RuntimeException("Invalid refresh token", e);
} }
} }
@ -679,8 +664,8 @@ public class OAuthClient {
} }
public Map<String, String> getCurrentQuery() { public Map<String, String> getCurrentQuery() {
Map<String, String> m = new HashMap<String, String>(); Map<String, String> m = new HashMap<>();
List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8"); List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), Charset.forName("UTF-8"));
for (NameValuePair p : pairs) { for (NameValuePair p : pairs) {
m.put(p.getName(), p.getValue()); m.put(p.getName(), p.getValue());
} }
@ -688,7 +673,7 @@ public class OAuthClient {
} }
public Map<String, String> getCurrentFragment() { public Map<String, String> getCurrentFragment() {
Map<String, String> m = new HashMap<String, String>(); Map<String, String> m = new HashMap<>();
String fragment = getCurrentUri().getRawFragment(); String fragment = getCurrentUri().getRawFragment();
List<NameValuePair> pairs = (fragment == null || fragment.isEmpty()) ? Collections.emptyList() : URLEncodedUtils.parse(fragment, Charset.forName("UTF-8")); List<NameValuePair> pairs = (fragment == null || fragment.isEmpty()) ? Collections.emptyList() : URLEncodedUtils.parse(fragment, Charset.forName("UTF-8"));
@ -1013,7 +998,7 @@ public class OAuthClient {
Assert.fail("Invalid content type. Status: " + statusCode + ", contentType: " + contentType); Assert.fail("Invalid content type. Status: " + statusCode + ", contentType: " + contentType);
} }
String s = IOUtils.toString(response.getEntity().getContent()); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
Map responseJson = JsonSerialization.readValue(s, Map.class); Map responseJson = JsonSerialization.readValue(s, Map.class);
if (statusCode == 200) { if (statusCode == 200) {

View file

@ -49,6 +49,7 @@ import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.Arrays; import java.util.Arrays;
@ -295,7 +296,7 @@ public class SamlClient {
* @return * @return
*/ */
public static SAMLDocumentHolder extractSamlResponseFromRedirect(String responseUri) { public static SAMLDocumentHolder extractSamlResponseFromRedirect(String responseUri) {
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(responseUri), "UTF-8"); List<NameValuePair> params = URLEncodedUtils.parse(URI.create(responseUri), Charset.forName("UTF-8"));
String samlDoc = null; String samlDoc = null;
for (NameValuePair param : params) { for (NameValuePair param : params) {

View file

@ -89,7 +89,7 @@ public class Timer {
private void logOperation(String operation, long duration) { private void logOperation(String operation, long duration) {
if (!stats.containsKey(operation)) { if (!stats.containsKey(operation)) {
stats.put(operation, new ArrayList<Long>()); stats.put(operation, new ArrayList<>());
} }
stats.get(operation).add(duration); stats.get(operation).add(duration);
log.info(String.format("Operation '%s' took: %s ms", operation, duration)); log.info(String.format("Operation '%s' took: %s ms", operation, duration));
@ -133,8 +133,8 @@ public class Timer {
} }
OutputStream stream = new BufferedOutputStream(new FileOutputStream(f)); OutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
for (Long duration : stats.get(op)) { for (Long duration : stats.get(op)) {
IOUtils.write(duration.toString(), stream); IOUtils.write(duration.toString(), stream, "UTF-8");
IOUtils.write("\n", stream); IOUtils.write("\n", stream, "UTF-8");
} }
stream.flush(); stream.flush();
IOUtils.closeQuietly(stream); IOUtils.closeQuietly(stream);

View file

@ -89,6 +89,7 @@ public final class URLUtils {
return urlCheck(condition, false); return urlCheck(condition, false);
} }
@SuppressWarnings("unchecked")
private static boolean urlCheck(ExpectedCondition condition, boolean secondTry) { private static boolean urlCheck(ExpectedCondition condition, boolean secondTry) {
WebDriver driver = getCurrentDriver(); WebDriver driver = getCurrentDriver();

View file

@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -125,7 +126,7 @@ public class ModifySamlResponseStepBuilder extends SamlDocumentStepBuilder<SAML2
String location = currentResponse.getFirstHeader("Location").getValue(); String location = currentResponse.getFirstHeader("Location").getValue();
URI locationUri = URI.create(location); URI locationUri = URI.create(location);
List<NameValuePair> params = URLEncodedUtils.parse(locationUri, "UTF-8"); List<NameValuePair> params = URLEncodedUtils.parse(locationUri, Charset.forName("UTF-8"));
for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) { for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
NameValuePair param = it.next(); NameValuePair param = it.next();
if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) { if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) {

View file

@ -112,6 +112,7 @@ public abstract class SamlDocumentStepBuilder<T extends SAML2Object, This extend
return (This) this; return (This) this;
} }
@SuppressWarnings("unchecked")
public This transformDocument(Saml2DocumentTransformer tr) { public This transformDocument(Saml2DocumentTransformer tr) {
final StringTransformer original = this.transformer; final StringTransformer original = this.transformer;
this.transformer = s -> { this.transformer = s -> {
@ -127,6 +128,7 @@ public abstract class SamlDocumentStepBuilder<T extends SAML2Object, This extend
return (This) this; return (This) this;
} }
@SuppressWarnings("unchecked")
public This transformString(StringTransformer tr) { public This transformString(StringTransformer tr) {
final StringTransformer original = this.transformer; final StringTransformer original = this.transformer;
this.transformer = s -> { this.transformer = s -> {

View file

@ -233,7 +233,7 @@ public abstract class AbstractAdapterTest extends AbstractAuthTest {
public static void addContextXml(Archive archive, String contextPath) { public static void addContextXml(Archive archive, String contextPath) {
try { try {
String contextXmlContent = IOUtils.toString(tomcatContext.openStream()) String contextXmlContent = IOUtils.toString(tomcatContext.openStream(), "UTF-8")
.replace("%CONTEXT_PATH%", contextPath); .replace("%CONTEXT_PATH%", contextPath);
archive.add(new StringAsset(contextXmlContent), "/META-INF/context.xml"); archive.add(new StringAsset(contextXmlContent), "/META-INF/context.xml");
} catch (IOException ex) { } catch (IOException ex) {
@ -242,7 +242,7 @@ public abstract class AbstractAdapterTest extends AbstractAuthTest {
} }
private static void enableHTTPSForAppServer() throws CommandFailedException, InterruptedException, TimeoutException, IOException, CliException, OperationException { private static void enableHTTPSForAppServer() throws CommandFailedException, InterruptedException, TimeoutException, IOException, CliException, OperationException {
OnlineManagementClient client = AppServerTestEnricher.getManagementClient(); try (OnlineManagementClient client = AppServerTestEnricher.getManagementClient()) {
Administration administration = new Administration(client); Administration administration = new Administration(client);
Operations operations = new Operations(client); Operations operations = new Operations(client);
@ -280,7 +280,7 @@ public abstract class AbstractAdapterTest extends AbstractAuthTest {
} }
administration.reloadIfRequired(); administration.reloadIfRequired();
client.close(); }
} }
} }

View file

@ -63,7 +63,7 @@ public abstract class AbstractExampleAdapterTest extends AbstractAdapterTest {
protected static WebArchive exampleDeployment(String name, String contextPath) throws IOException { protected static WebArchive exampleDeployment(String name, String contextPath) throws IOException {
URL webXML = Paths.get(EXAMPLES_WEB_XML).toUri().toURL(); URL webXML = Paths.get(EXAMPLES_WEB_XML).toUri().toURL();
String webXmlContent = IOUtils.toString(webXML.openStream()) String webXmlContent = IOUtils.toString(webXML.openStream(), "UTF-8")
.replace("%CONTEXT_PATH%", contextPath); .replace("%CONTEXT_PATH%", contextPath);
WebArchive webArchive = ShrinkWrap.createFromZipFile(WebArchive.class, WebArchive webArchive = ShrinkWrap.createFromZipFile(WebArchive.class,
new File(EXAMPLES_HOME + "/" + name + "-" + EXAMPLES_VERSION_SUFFIX + ".war")) new File(EXAMPLES_HOME + "/" + name + "-" + EXAMPLES_VERSION_SUFFIX + ".war"))

View file

@ -29,6 +29,7 @@ import org.openqa.selenium.By;
import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilder;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset;
import java.util.List; import java.util.List;
import org.junit.Assert; import org.junit.Assert;
@ -92,7 +93,7 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest {
String webXMLContent; String webXMLContent;
try { try {
webXMLContent = IOUtils.toString(webXML.openStream()) webXMLContent = IOUtils.toString(webXML.openStream(), Charset.forName("UTF-8"))
.replace("%CONTEXT_PATH%", name); .replace("%CONTEXT_PATH%", name);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View file

@ -251,7 +251,7 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractExampleAd
ClientResource resourceServerClient = getClientResource(RESOURCE_SERVER_ID); ClientResource resourceServerClient = getClientResource(RESOURCE_SERVER_ID);
RoleResource manageAlbumRole = resourceServerClient.roles().get("manage-albums"); RoleResource manageAlbumRole = resourceServerClient.roles().get("manage-albums");
RoleRepresentation roleRepresentation = manageAlbumRole.toRepresentation(); RoleRepresentation roleRepresentation = manageAlbumRole.toRepresentation();
List<Map> roles = JsonSerialization.readValue(policy.getConfig().get("roles"), List.class); List<Map<String, Object>> roles = JsonSerialization.readValue(policy.getConfig().get("roles"), List.class);
roles = roles.stream().filter((Map map) -> !map.get("id").equals(roleRepresentation.getId())).collect(Collectors.toList()); roles = roles.stream().filter((Map map) -> !map.get("id").equals(roleRepresentation.getId())).collect(Collectors.toList());
@ -389,7 +389,7 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractExampleAd
for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) { for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) {
if ("Any User Policy".equals(policy.getName())) { if ("Any User Policy".equals(policy.getName())) {
List<Map> roles = JsonSerialization.readValue(policy.getConfig().get("roles"), List.class); List<Map<String, Object>> roles = JsonSerialization.readValue(policy.getConfig().get("roles"), List.class);
roles.forEach(role -> { roles.forEach(role -> {
String roleId = (String) role.get("id"); String roleId = (String) role.get("id");

View file

@ -46,7 +46,6 @@ import org.openqa.selenium.Cookie;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.adapters.OIDCAuthenticationError; import org.keycloak.adapters.OIDCAuthenticationError;
import org.keycloak.common.Version;
import org.keycloak.common.util.Time; import org.keycloak.common.util.Time;
import org.keycloak.constants.AdapterConstants; import org.keycloak.constants.AdapterConstants;
import org.keycloak.events.Details; import org.keycloak.events.Details;
@ -979,7 +978,7 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
if (serverLogPath != null) { if (serverLogPath != null) {
log.info("Checking app server log at: " + serverLogPath); log.info("Checking app server log at: " + serverLogPath);
File serverLog = new File(serverLogPath); File serverLog = new File(serverLogPath);
String serverLogContent = FileUtils.readFileToString(serverLog); String serverLogContent = FileUtils.readFileToString(serverLog, "UTF-8");
UserRepresentation bburke = ApiUtil.findUserByUsername(testRealmResource(), "bburke@redhat.com"); UserRepresentation bburke = ApiUtil.findUserByUsername(testRealmResource(), "bburke@redhat.com");
Pattern pattern = Pattern.compile("User '" + bburke.getId() + "' invoking '" + appServerUrl + "customer-portal[^\\s]+' on client 'customer-portal'"); Pattern pattern = Pattern.compile("User '" + bburke.getId() + "' invoking '" + appServerUrl + "customer-portal[^\\s]+' on client 'customer-portal'");

View file

@ -19,6 +19,7 @@ package org.keycloak.testsuite.adapter.servlet;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@ -26,9 +27,9 @@ import javax.ws.rs.core.UriBuilder;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.graphene.page.Page;
import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.api.spec.WebArchive;
@ -60,7 +61,9 @@ import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.util.URLAssert; import org.keycloak.testsuite.util.URLAssert;
import org.openqa.selenium.By; import org.openqa.selenium.By;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.auth.page.AuthRealm.DEMO; import static org.keycloak.testsuite.auth.page.AuthRealm.DEMO;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlEquals; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlEquals;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
@ -307,8 +310,7 @@ public abstract class AbstractOIDCPublicKeyRotationAdapterTest extends AbstractS
private int invokeRESTEndpoint(String accessTokenString) { private int invokeRESTEndpoint(String accessTokenString) {
HttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
String restUrl = customerDb.toString(); String restUrl = customerDb.toString();
HttpGet get = new HttpGet(restUrl); HttpGet get = new HttpGet(restUrl);
get.addHeader("Authorization", "Bearer " + accessTokenString); get.addHeader("Authorization", "Bearer " + accessTokenString);
@ -320,19 +322,16 @@ public abstract class AbstractOIDCPublicKeyRotationAdapterTest extends AbstractS
} }
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); try (InputStream is = entity.getContent()) {
try { String body = StreamUtil.readString(is, Charset.forName("UTF-8"));
String body = StreamUtil.readString(is);
Assert.assertTrue(body.contains("Stian Thorgersen") && body.contains("Bill Burke")); Assert.assertTrue(body.contains("Stian Thorgersen") && body.contains("Bill Burke"));
return status; return status;
} finally {
is.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} finally { } catch (IOException e) {
client.getConnectionManager().shutdown(); throw new RuntimeException(e);
} }
} }

View file

@ -338,7 +338,7 @@ public class ComponentsTest extends AbstractAdminTest {
rep.setProviderType(TestProvider.class.getName()); rep.setProviderType(TestProvider.class.getName());
rep.setSubType("foo"); rep.setSubType("foo");
MultivaluedHashMap config = new MultivaluedHashMap(); MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
rep.setConfig(config); rep.setConfig(config);
return rep; return rep;
} }

View file

@ -618,12 +618,12 @@ public class IdentityProviderTest extends AbstractAdminTest {
Assert.assertTrue("AuthnRequestsSigned", desc.isAuthnRequestsSigned()); Assert.assertTrue("AuthnRequestsSigned", desc.isAuthnRequestsSigned());
Set<String> expected = new HashSet(Arrays.asList( Set<String> expected = new HashSet<>(Arrays.asList(
"urn:oasis:names:tc:SAML:2.0:protocol", "urn:oasis:names:tc:SAML:2.0:protocol",
"urn:oasis:names:tc:SAML:1.1:protocol", "urn:oasis:names:tc:SAML:1.1:protocol",
"http://schemas.xmlsoap.org/ws/2003/07/secext")); "http://schemas.xmlsoap.org/ws/2003/07/secext"));
Set<String> actual = new HashSet(desc.getProtocolSupportEnumeration()); Set<String> actual = new HashSet<>(desc.getProtocolSupportEnumeration());
Assert.assertEquals("ProtocolSupportEnumeration", expected, actual); Assert.assertEquals("ProtocolSupportEnumeration", expected, actual);

View file

@ -94,7 +94,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
// Find existent // Find existent
RequiredActionProviderRepresentation rep = authMgmtResource.getRequiredAction(DummyRequiredActionFactory.PROVIDER_ID); RequiredActionProviderRepresentation rep = authMgmtResource.getRequiredAction(DummyRequiredActionFactory.PROVIDER_ID);
compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action", compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action",
true, false, Collections.emptyMap())); true, false, Collections.<String, String>emptyMap()));
// Update not-existent - should fail // Update not-existent - should fail
try { try {
@ -109,7 +109,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
authMgmtResource.updateRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, rep); authMgmtResource.updateRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, rep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), rep, ResourceType.REQUIRED_ACTION); assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), rep, ResourceType.REQUIRED_ACTION);
compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action", compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action",
true, true, Collections.emptyMap())); true, true, Collections.<String, String>emptyMap()));
// Remove unexistent - should fail // Remove unexistent - should fail
try { try {
@ -157,14 +157,14 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
Assert.assertEquals("name - " + expected.getAlias(), expected.getName(), actual.getName()); Assert.assertEquals("name - " + expected.getAlias(), expected.getName(), actual.getName());
Assert.assertEquals("enabled - " + expected.getAlias(), expected.isEnabled(), actual.isEnabled()); Assert.assertEquals("enabled - " + expected.getAlias(), expected.isEnabled(), actual.isEnabled());
Assert.assertEquals("defaultAction - " + expected.getAlias(), expected.isDefaultAction(), actual.isDefaultAction()); Assert.assertEquals("defaultAction - " + expected.getAlias(), expected.isDefaultAction(), actual.isDefaultAction());
Assert.assertEquals("config - " + expected.getAlias(), expected.getConfig() != null ? expected.getConfig() : Collections.emptyMap(), actual.getConfig()); Assert.assertEquals("config - " + expected.getAlias(), expected.getConfig() != null ? expected.getConfig() : Collections.<String, String>emptyMap(), actual.getConfig());
} }
private void addRequiredAction(List<RequiredActionProviderRepresentation> target, String alias, String name, boolean enabled, boolean defaultAction, Map conf) { private void addRequiredAction(List<RequiredActionProviderRepresentation> target, String alias, String name, boolean enabled, boolean defaultAction, Map<String, String> conf) {
target.add(newRequiredAction(alias, name, enabled, defaultAction, conf)); target.add(newRequiredAction(alias, name, enabled, defaultAction, conf));
} }
private RequiredActionProviderRepresentation newRequiredAction(String alias, String name, boolean enabled, boolean defaultAction, Map conf) { private RequiredActionProviderRepresentation newRequiredAction(String alias, String name, boolean enabled, boolean defaultAction, Map<String, String> conf) {
RequiredActionProviderRepresentation action = new RequiredActionProviderRepresentation(); RequiredActionProviderRepresentation action = new RequiredActionProviderRepresentation();
action.setAlias(alias); action.setAlias(alias);
action.setName(name); action.setName(name);

View file

@ -16,10 +16,8 @@
*/ */
package org.keycloak.testsuite.admin.client.authorization; package org.keycloak.testsuite.admin.client.authorization;
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;

View file

@ -21,6 +21,7 @@ import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
import static org.keycloak.testsuite.admin.ApiUtil.findClientByClientId; import static org.keycloak.testsuite.admin.ApiUtil.findClientByClientId;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset;
import java.security.Principal; import java.security.Principal;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
@ -38,9 +39,8 @@ import javax.ws.rs.core.Response;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials; import org.apache.http.auth.Credentials;
import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSCredential;
import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.graphene.page.Page;
@ -115,6 +115,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
@Before @Before
@Override
public void beforeAbstractKeycloakTest() throws Exception { public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest(); super.beforeAbstractKeycloakTest();
@ -136,6 +137,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
} }
@After @After
@Override
public void afterAbstractKeycloakTest() { public void afterAbstractKeycloakTest() {
cleanupApacheHttpClient(); cleanupApacheHttpClient();
@ -352,15 +354,17 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
.disableCookieCache(false) .disableCookieCache(false)
.build(); .build();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory); httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);
if (useSpnego) { if (useSpnego) {
Credentials fake = new Credentials() { Credentials fake = new Credentials() {
@Override
public String getPassword() { public String getPassword() {
return null; return null;
} }
@Override
public Principal getUserPrincipal() { public Principal getUserPrincipal() {
return null; return null;
} }
@ -409,7 +413,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
protected OAuthClient.AccessTokenResponse assertAuthenticationSuccess(String codeUrl) throws Exception { protected OAuthClient.AccessTokenResponse assertAuthenticationSuccess(String codeUrl) throws Exception {
List<NameValuePair> pairs = URLEncodedUtils.parse(new URI(codeUrl), "UTF-8"); List<NameValuePair> pairs = URLEncodedUtils.parse(new URI(codeUrl), Charset.forName("UTF-8"));
String code = null; String code = null;
String state = null; String state = null;
for (NameValuePair pair : pairs) { for (NameValuePair pair : pairs) {
@ -444,6 +448,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider); testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);
} }
@Override
public RealmResource testRealmResource() { public RealmResource testRealmResource() {
return adminClient.realm("test"); return adminClient.realm("test");
} }

View file

@ -59,6 +59,7 @@ public class KeycloakSPNegoSchemeFactory extends SPNegoSchemeFactory {
@Override @Override
@SuppressWarnings("deprecation")
public AuthScheme newInstance(HttpParams params) { public AuthScheme newInstance(HttpParams params) {
return new KeycloakSPNegoScheme(isStripPort(), isUseCanonicalHostname()); return new KeycloakSPNegoScheme(isStripPort(), isUseCanonicalHostname());
} }

View file

@ -18,7 +18,7 @@ package org.keycloak.testsuite.i18n;
import java.util.Arrays; import java.util.Arrays;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
@ -118,7 +118,7 @@ public class LoginPageTest extends AbstractI18NTest {
public void acceptLanguageHeader() { public void acceptLanguageHeader() {
ProfileAssume.assumeCommunity(); ProfileAssume.assumeCommunity();
DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build(); CloseableHttpClient httpClient = (CloseableHttpClient) new HttpClientBuilder().build();
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

View file

@ -30,13 +30,6 @@ import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import javax.ws.rs.NotFoundException; import javax.ws.rs.NotFoundException;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.keycloak.testsuite.Assert.assertEquals;
import static org.keycloak.testsuite.Assert.assertFalse;
import static org.keycloak.testsuite.Assert.assertNames;
import static org.keycloak.testsuite.Assert.assertTrue;
import static org.keycloak.testsuite.Assert.fail;
import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER; import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER;
/** /**

View file

@ -22,7 +22,7 @@ import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -34,7 +34,6 @@ import org.keycloak.admin.client.resource.ClientTemplateResource;
import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource; import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.common.enums.SslRequired; import org.keycloak.common.enums.SslRequired;
import org.keycloak.common.util.Time;
import org.keycloak.events.Details; import org.keycloak.events.Details;
import org.keycloak.events.Errors; import org.keycloak.events.Errors;
import org.keycloak.jose.jws.JWSHeader; import org.keycloak.jose.jws.JWSHeader;
@ -952,27 +951,23 @@ public class AccessTokenTest extends AbstractKeycloakTest {
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE); String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(oauth.getAccessTokenUrl()); HttpPost post = new HttpPost(oauth.getAccessTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code)); parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri())); parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, oauth.getClientId())); parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, oauth.getClientId()));
post.setHeader("Authorization", "Negotiate something-which-will-be-ignored"); post.setHeader("Authorization", "Negotiate something-which-will-be-ignored");
UrlEncodedFormEntity formEntity = null; UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
post.setEntity(formEntity); post.setEntity(formEntity);
OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post)); OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
Assert.assertEquals(200, response.getStatusCode()); Assert.assertEquals(200, response.getStatusCode());
AccessToken token = oauth.verifyToken(response.getAccessToken()); AccessToken token = oauth.verifyToken(response.getAccessToken());
events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent(); events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent();
} finally {
oauth.closeClient(client);
} }
} }

View file

@ -17,11 +17,12 @@
package org.keycloak.testsuite.oauth; package org.keycloak.testsuite.oauth;
import java.io.IOException;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Rule; import org.junit.Rule;
@ -90,11 +91,10 @@ public class ClientAuthPostMethodTest extends AbstractKeycloakTest {
private OAuthClient.AccessTokenResponse doAccessTokenRequestPostAuth(String code, String clientSecret) { private OAuthClient.AccessTokenResponse doAccessTokenRequestPostAuth(String code, String clientSecret) {
CloseableHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(oauth.getAccessTokenUrl()); HttpPost post = new HttpPost(oauth.getAccessTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>(); List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE)); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code)); parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri())); parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
@ -116,8 +116,8 @@ public class ClientAuthPostMethodTest extends AbstractKeycloakTest {
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e); throw new RuntimeException("Failed to retrieve access token", e);
} }
} finally { } catch (IOException e) {
oauth.closeClient(client); throw new RuntimeException(e);
} }
} }

View file

@ -34,8 +34,6 @@ import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test; import org.junit.Test;
import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.common.Version;
import org.keycloak.models.Constants; import org.keycloak.models.Constants;
import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
@ -49,8 +47,6 @@ import java.net.URLEncoder;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -71,8 +67,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
public void checkIframe() throws IOException { public void checkIframe() throws IOException {
CookieStore cookieStore = new BasicCookieStore(); CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) {
try {
String redirectUri = URLEncoder.encode(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8"); String redirectUri = URLEncoder.encode(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8");
HttpGet get = new HttpGet( HttpGet get = new HttpGet(
@ -80,7 +75,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
"&redirect_uri=" + redirectUri); "&redirect_uri=" + redirectUri);
CloseableHttpResponse response = client.execute(get); CloseableHttpResponse response = client.execute(get);
String s = IOUtils.toString(response.getEntity().getContent()); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
response.close(); response.close();
String action = ActionURIUtils.getActionURIFromPageSource(s); String action = ActionURIUtils.getActionURIFromPageSource(s);
@ -131,7 +126,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
response = client.execute(get); response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
s = IOUtils.toString(response.getEntity().getContent()); s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
assertTrue(s.contains("function getCookie()")); assertTrue(s.contains("function getCookie()"));
assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue());
@ -166,8 +161,6 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
response = client.execute(get); response = client.execute(get);
assertEquals(204, response.getStatusLine().getStatusCode()); assertEquals(204, response.getStatusLine().getStatusCode());
response.close(); response.close();
} finally {
client.close();
} }
} }
@ -177,8 +170,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
ClientResource master = adminClient.realm("master").clients().get(id); ClientResource master = adminClient.realm("master").clients().get(id);
ClientRepresentation rep = master.toRepresentation(); ClientRepresentation rep = master.toRepresentation();
List<String> org = rep.getWebOrigins(); List<String> org = rep.getWebOrigins();
CloseableHttpClient client = HttpClients.createDefault(); try (CloseableHttpClient client = HttpClients.createDefault()) {
try {
rep.setWebOrigins(Collections.singletonList("*")); rep.setWebOrigins(Collections.singletonList("*"));
master.update(rep); master.update(rep);
@ -186,13 +178,12 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
+ "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID
+ "&origin=" + "http://anything" + "&origin=" + "http://anything"
); );
CloseableHttpResponse response = client.execute(get); try (CloseableHttpResponse response = client.execute(get)) {
assertEquals(204, response.getStatusLine().getStatusCode()); assertEquals(204, response.getStatusLine().getStatusCode());
response.close(); }
} finally { } finally {
rep.setWebOrigins(org); rep.setWebOrigins(org);
master.update(rep); master.update(rep);
client.close();
} }
} }
@ -200,8 +191,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
public void checkIframeCache() throws IOException { public void checkIframeCache() throws IOException {
String version = testingClient.server().fetch(new ServerVersion()); String version = testingClient.server().fetch(new ServerVersion());
CloseableHttpClient client = HttpClients.createDefault(); try (CloseableHttpClient client = HttpClients.createDefault()) {
try {
HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html");
CloseableHttpResponse response = client.execute(get); CloseableHttpResponse response = client.execute(get);
@ -213,8 +203,6 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age")); assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age"));
} finally {
client.close();
} }
} }

View file

@ -1,86 +1,38 @@
package org.keycloak.testsuite.oauth; package org.keycloak.testsuite.oauth;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException; import org.keycloak.OAuthErrorException;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientTemplateResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.common.enums.SslRequired;
import org.keycloak.common.util.Base64Url; import org.keycloak.common.util.Base64Url;
import org.keycloak.events.Details; import org.keycloak.events.Details;
import org.keycloak.events.Errors; import org.keycloak.events.Errors;
import org.keycloak.jose.jws.JWSHeader; import org.keycloak.jose.jws.JWSHeader;
import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.Constants;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.protocol.oidc.mappers.HardcodedClaim;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.RefreshToken; import org.keycloak.representations.RefreshToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ClientTemplateRepresentation;
import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.ClientManager; import org.keycloak.testsuite.util.ClientManager;
import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.RealmManager;
import org.keycloak.testsuite.util.RoleBuilder;
import org.keycloak.testsuite.util.UserBuilder; import org.keycloak.testsuite.util.UserBuilder;
import org.keycloak.testsuite.util.UserInfoClientUtil;
import org.keycloak.testsuite.util.UserManager;
import org.keycloak.util.BasicAuthHelper;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
import static org.keycloak.testsuite.admin.ApiUtil.findClientByClientId;
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername; import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsernameId;
import static org.keycloak.testsuite.util.OAuthClient.AUTH_SERVER_ROOT;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createRoleNameMapper;
//https://tools.ietf.org/html/rfc7636 //https://tools.ietf.org/html/rfc7636

View file

@ -277,7 +277,7 @@ public class OIDCProtocolMappersTest extends AbstractKeycloakTest {
Object nulll = idToken.getOtherClaims().get("null"); Object nulll = idToken.getOtherClaims().get("null");
assertNull(nulll); assertNull(nulll);
AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); oauth.verifyToken(response.getAccessToken());
oauth.openLogout(); oauth.openLogout();
} }

View file

@ -19,7 +19,8 @@ package org.keycloak.testsuite.oauth;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
@ -59,7 +60,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
private static String userId2; private static String userId2;
private TimeBasedOTP totp = new TimeBasedOTP(); private final TimeBasedOTP totp = new TimeBasedOTP();
@Rule @Rule
public AssertEvents events = new AssertEvents(this); public AssertEvents events = new AssertEvents(this);
@ -430,8 +431,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
public void grantAccessTokenMissingGrantType() throws Exception { public void grantAccessTokenMissingGrantType() throws Exception {
oauth.clientId("resource-owner"); oauth.clientId("resource-owner");
DefaultHttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
try {
HttpPost post = new HttpPost(oauth.getResourceOwnerPasswordCredentialGrantUrl()); HttpPost post = new HttpPost(oauth.getResourceOwnerPasswordCredentialGrantUrl());
OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post)); OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
@ -439,8 +439,6 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
assertEquals("invalid_request", response.getError()); assertEquals("invalid_request", response.getError());
assertEquals("Missing form parameter: grant_type", response.getErrorDescription()); assertEquals("Missing form parameter: grant_type", response.getErrorDescription());
} finally {
client.close();
} }
} }

View file

@ -25,6 +25,7 @@ import org.openqa.selenium.WebDriver;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset;
/** /**
* *
@ -75,7 +76,7 @@ public class TestEventsLogger extends RunListener {
if (driver != null && driver.getPageSource() != null) { if (driver != null && driver.getPageSource() != null) {
String pageSourceLocation = System.getProperty("page.source.location", "target/failed-tests/page-source/"); String pageSourceLocation = System.getProperty("page.source.location", "target/failed-tests/page-source/");
FileUtils.writeStringToFile(new File(pageSourceLocation + d.getTestClass().getSimpleName() + "/" + d.getMethodName() + ".html"), FileUtils.writeStringToFile(new File(pageSourceLocation + d.getTestClass().getSimpleName() + "/" + d.getMethodName() + ".html"),
driver.getPageSource()); driver.getPageSource(), Charset.forName("UTF-8"));
} }
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Logger.getLogger(TestEventsLogger.class).warn(ex.getMessage()); Logger.getLogger(TestEventsLogger.class).warn(ex.getMessage());

View file

@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserRepresentation;
@ -72,7 +71,7 @@ public class UserBuilder {
*/ */
public UserBuilder addPassword(String password) { public UserBuilder addPassword(String password) {
if (rep.getCredentials() == null) { if (rep.getCredentials() == null) {
rep.setCredentials(new LinkedList<CredentialRepresentation>()); rep.setCredentials(new LinkedList<>());
} }
CredentialRepresentation credential = new CredentialRepresentation(); CredentialRepresentation credential = new CredentialRepresentation();
@ -103,20 +102,18 @@ public class UserBuilder {
public UserBuilder addRoles(String... roles) { public UserBuilder addRoles(String... roles) {
if (rep.getRealmRoles() == null) { if (rep.getRealmRoles() == null) {
rep.setRealmRoles(new ArrayList<String>()); rep.setRealmRoles(new ArrayList<>());
}
for (String role : roles) {
rep.getRealmRoles().add(role);
} }
rep.getRealmRoles().addAll(Arrays.asList(roles));
return this; return this;
} }
public UserBuilder role(String client, String role) { public UserBuilder role(String client, String role) {
if (rep.getClientRoles() == null) { if (rep.getClientRoles() == null) {
rep.setClientRoles(new HashMap<String, List<String>>()); rep.setClientRoles(new HashMap<>());
} }
if (rep.getClientRoles().get(client) == null) { if (rep.getClientRoles().get(client) == null) {
rep.getClientRoles().put(client, new LinkedList<String>()); rep.getClientRoles().put(client, new LinkedList<>());
} }
rep.getClientRoles().get(client).add(role); rep.getClientRoles().get(client).add(role);
return this; return this;
@ -124,7 +121,7 @@ public class UserBuilder {
public UserBuilder requiredAction(String requiredAction) { public UserBuilder requiredAction(String requiredAction) {
if (rep.getRequiredActions() == null) { if (rep.getRequiredActions() == null) {
rep.setRequiredActions(new LinkedList<String>()); rep.setRequiredActions(new LinkedList<>());
} }
rep.getRequiredActions().add(requiredAction); rep.getRequiredActions().add(requiredAction);
return this; return this;
@ -137,7 +134,7 @@ public class UserBuilder {
public UserBuilder secret(String type, String secret) { public UserBuilder secret(String type, String secret) {
if (rep.getCredentials() == null) { if (rep.getCredentials() == null) {
rep.setCredentials(new LinkedList<CredentialRepresentation>()); rep.setCredentials(new LinkedList<>());
} }
CredentialRepresentation credential = new CredentialRepresentation(); CredentialRepresentation credential = new CredentialRepresentation();