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) {
return UriBuilder.fromUri(actionURI)
.replaceQueryParam(paramName, null)
.replaceQueryParam(paramName, (Object[]) null)
.build().toString();
}

View file

@ -46,7 +46,7 @@ public class ProfileAssume {
ProfileInfoRepresentation profileInfo = adminClient.serverInfo().getInfo().getProfileInfo();
profile = profileInfo.getName();
List<String> disabled = profileInfo.getDisabledFeatures();
disabledFeatures = Collections.unmodifiableSet(new HashSet(disabled));
disabledFeatures = Collections.unmodifiableSet(new HashSet<>(disabled));
adminClient.close();
} catch (Exception 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.concurrent.ConcurrentHashMap;
import javax.ws.rs.NotFoundException;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.client.KeycloakTestingClient;
@ -44,7 +42,7 @@ public final class TestContext {
private boolean adminLoggedIn;
private final Map customContext = new HashMap<>();
private final Map<Object, Object> customContext = new HashMap<>();
private Keycloak adminClient;
private KeycloakTestingClient testingClient;
@ -55,7 +53,7 @@ public final class TestContext {
private boolean initialized;
// 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) {
this.suiteContext = suiteContext;

View file

@ -57,7 +57,7 @@ public class Registry implements ContainerRegistry {
private final List<Container> containers;
private Injector injector;
private final Injector injector;
private static final Logger logger = Logger.getLogger(RegistryCreator.class.getName());
@ -98,7 +98,7 @@ public class Registry implements ContainerRegistry {
return addContainer(injector.inject(
new ContainerImpl(definition.getContainerName(), dcService, definition)));
} catch (Exception e) {
} catch (ConfigurationException 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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
@ -41,20 +41,14 @@ public class MigrationContext {
String file = getOfflineTokenLocation();
logger.infof("Reading previously saved offline token from the file: %s", file);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
String offlineToken = StreamUtil.readString(fis);
try (FileInputStream fis = new FileInputStream(file)) {
String offlineToken = StreamUtil.readString(fis, Charset.forName("UTF-8"));
File f = new File(file);
f.delete();
logger.infof("Deleted file with offline token: %s", file);
return offlineToken;
} finally {
if (fis != null) {
fis.close();
}
}
}
@ -85,14 +79,8 @@ public class MigrationContext {
String file = getOfflineTokenLocation();
logger.infof("Saving offline token to file: %s", file);
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
writer.print(offlineToken);
} finally {
if (writer != null) {
writer.close();
}
}
}
@ -103,4 +91,4 @@ public class MigrationContext {
return System.getProperty("basedir") + "/offline-token.txt";
}
}
}

View file

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

View file

@ -35,7 +35,7 @@ public class LogChecker {
public static void checkServerLog(File logFile) throws IOException {
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) {
boolean containsError = logText.contains("ERROR") || logText.contains("SEVERE") || logText.contains("Exception ");

View file

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

View file

@ -49,6 +49,7 @@ import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
@ -295,7 +296,7 @@ public class SamlClient {
* @return
*/
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;
for (NameValuePair param : params) {
@ -398,4 +399,4 @@ public class SamlClient {
protected HttpClientBuilder createHttpClientBuilderInstance() {
return HttpClientBuilder.create();
}
}
}

View file

@ -89,7 +89,7 @@ public class Timer {
private void logOperation(String operation, long duration) {
if (!stats.containsKey(operation)) {
stats.put(operation, new ArrayList<Long>());
stats.put(operation, new ArrayList<>());
}
stats.get(operation).add(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));
for (Long duration : stats.get(op)) {
IOUtils.write(duration.toString(), stream);
IOUtils.write("\n", stream);
IOUtils.write(duration.toString(), stream, "UTF-8");
IOUtils.write("\n", stream, "UTF-8");
}
stream.flush();
IOUtils.closeQuietly(stream);

View file

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

View file

@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@ -125,7 +126,7 @@ public class ModifySamlResponseStepBuilder extends SamlDocumentStepBuilder<SAML2
String location = currentResponse.getFirstHeader("Location").getValue();
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();) {
NameValuePair param = it.next();
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;
}
@SuppressWarnings("unchecked")
public This transformDocument(Saml2DocumentTransformer tr) {
final StringTransformer original = this.transformer;
this.transformer = s -> {
@ -127,6 +128,7 @@ public abstract class SamlDocumentStepBuilder<T extends SAML2Object, This extend
return (This) this;
}
@SuppressWarnings("unchecked")
public This transformString(StringTransformer tr) {
final StringTransformer original = this.transformer;
this.transformer = s -> {

View file

@ -233,7 +233,7 @@ public abstract class AbstractAdapterTest extends AbstractAuthTest {
public static void addContextXml(Archive archive, String contextPath) {
try {
String contextXmlContent = IOUtils.toString(tomcatContext.openStream())
String contextXmlContent = IOUtils.toString(tomcatContext.openStream(), "UTF-8")
.replace("%CONTEXT_PATH%", contextPath);
archive.add(new StringAsset(contextXmlContent), "/META-INF/context.xml");
} catch (IOException ex) {
@ -242,45 +242,45 @@ public abstract class AbstractAdapterTest extends AbstractAuthTest {
}
private static void enableHTTPSForAppServer() throws CommandFailedException, InterruptedException, TimeoutException, IOException, CliException, OperationException {
OnlineManagementClient client = AppServerTestEnricher.getManagementClient();
Administration administration = new Administration(client);
Operations operations = new Operations(client);
if(!operations.exists(Address.coreService("management").and("security-realm", "UndertowRealm"))) {
client.execute("/core-service=management/security-realm=UndertowRealm:add()");
client.execute("/core-service=management/security-realm=UndertowRealm/server-identity=ssl:add(keystore-relative-to=jboss.server.config.dir,keystore-password=secret,keystore-path=adapter.jks");
}
client.execute("/system-property=javax.net.ssl.trustStore:add(value=${jboss.server.config.dir}/keycloak.truststore)");
client.execute("/system-property=javax.net.ssl.trustStorePassword:add(value=secret)");
if (APP_SERVER_CONTAINER.contains("eap6")) {
if(!operations.exists(Address.subsystem("web").and("connector", "https"))) {
client.apply(new AddConnector.Builder("https")
.protocol("HTTP/1.1")
.scheme("https")
.socketBinding("https")
.secure(true)
.build());
client.apply(new AddConnectorSslConfig.Builder("https")
.password("secret")
.certificateKeyFile("${jboss.server.config.dir}/adapter.jks")
try (OnlineManagementClient client = AppServerTestEnricher.getManagementClient()) {
Administration administration = new Administration(client);
Operations operations = new Operations(client);
if(!operations.exists(Address.coreService("management").and("security-realm", "UndertowRealm"))) {
client.execute("/core-service=management/security-realm=UndertowRealm:add()");
client.execute("/core-service=management/security-realm=UndertowRealm/server-identity=ssl:add(keystore-relative-to=jboss.server.config.dir,keystore-password=secret,keystore-path=adapter.jks");
}
client.execute("/system-property=javax.net.ssl.trustStore:add(value=${jboss.server.config.dir}/keycloak.truststore)");
client.execute("/system-property=javax.net.ssl.trustStorePassword:add(value=secret)");
if (APP_SERVER_CONTAINER.contains("eap6")) {
if(!operations.exists(Address.subsystem("web").and("connector", "https"))) {
client.apply(new AddConnector.Builder("https")
.protocol("HTTP/1.1")
.scheme("https")
.socketBinding("https")
.secure(true)
.build());
client.apply(new AddConnectorSslConfig.Builder("https")
.password("secret")
.certificateKeyFile("${jboss.server.config.dir}/adapter.jks")
.build());
}
} else {
client.apply(new RemoveUndertowListener.Builder(UndertowListenerType.HTTPS_LISTENER, "https")
.forDefaultServer());
administration.reloadIfRequired();
client.apply(new AddUndertowListener.HttpsBuilder("https", "default-server", "https")
.securityRealm("UndertowRealm")
.build());
}
} else {
client.apply(new RemoveUndertowListener.Builder(UndertowListenerType.HTTPS_LISTENER, "https")
.forDefaultServer());
administration.reloadIfRequired();
client.apply(new AddUndertowListener.HttpsBuilder("https", "default-server", "https")
.securityRealm("UndertowRealm")
.build());
}
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 {
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);
WebArchive webArchive = ShrinkWrap.createFromZipFile(WebArchive.class,
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 java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import org.junit.Assert;
@ -92,7 +93,7 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest {
String webXMLContent;
try {
webXMLContent = IOUtils.toString(webXML.openStream())
webXMLContent = IOUtils.toString(webXML.openStream(), Charset.forName("UTF-8"))
.replace("%CONTEXT_PATH%", name);
} catch (IOException e) {
throw new RuntimeException(e);

View file

@ -251,7 +251,7 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractExampleAd
ClientResource resourceServerClient = getClientResource(RESOURCE_SERVER_ID);
RoleResource manageAlbumRole = resourceServerClient.roles().get("manage-albums");
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());
@ -389,7 +389,7 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractExampleAd
for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) {
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 -> {
String roleId = (String) role.get("id");

View file

@ -46,7 +46,6 @@ import org.openqa.selenium.Cookie;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.adapters.OIDCAuthenticationError;
import org.keycloak.common.Version;
import org.keycloak.common.util.Time;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.events.Details;
@ -979,7 +978,7 @@ public abstract class AbstractDemoServletsAdapterTest extends AbstractServletsAd
if (serverLogPath != null) {
log.info("Checking app server log at: " + 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");
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.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
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.HttpResponse;
import org.apache.http.client.HttpClient;
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.graphene.page.Page;
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.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.util.URLAssert.assertCurrentUrlEquals;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
@ -307,8 +310,7 @@ public abstract class AbstractOIDCPublicKeyRotationAdapterTest extends AbstractS
private int invokeRESTEndpoint(String accessTokenString) {
HttpClient client = new DefaultHttpClient();
try {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
String restUrl = customerDb.toString();
HttpGet get = new HttpGet(restUrl);
get.addHeader("Authorization", "Bearer " + accessTokenString);
@ -320,19 +322,16 @@ public abstract class AbstractOIDCPublicKeyRotationAdapterTest extends AbstractS
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
try {
String body = StreamUtil.readString(is);
try (InputStream is = entity.getContent()) {
String body = StreamUtil.readString(is, Charset.forName("UTF-8"));
Assert.assertTrue(body.contains("Stian Thorgersen") && body.contains("Bill Burke"));
return status;
} finally {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} finally {
client.getConnectionManager().shutdown();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

View file

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

View file

@ -618,12 +618,12 @@ public class IdentityProviderTest extends AbstractAdminTest {
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:1.1:protocol",
"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);

View file

@ -94,7 +94,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
// Find existent
RequiredActionProviderRepresentation rep = authMgmtResource.getRequiredAction(DummyRequiredActionFactory.PROVIDER_ID);
compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action",
true, false, Collections.emptyMap()));
true, false, Collections.<String, String>emptyMap()));
// Update not-existent - should fail
try {
@ -109,7 +109,7 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
authMgmtResource.updateRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, rep);
assertAdminEvents.assertEvent(REALM_NAME, OperationType.UPDATE, AdminEventPaths.authRequiredActionPath(rep.getAlias()), rep, ResourceType.REQUIRED_ACTION);
compareRequiredAction(rep, newRequiredAction(DummyRequiredActionFactory.PROVIDER_ID, "Dummy Action",
true, true, Collections.emptyMap()));
true, true, Collections.<String, String>emptyMap()));
// Remove unexistent - should fail
try {
@ -157,14 +157,14 @@ public class RequiredActionsTest extends AbstractAuthenticationTest {
Assert.assertEquals("name - " + expected.getAlias(), expected.getName(), actual.getName());
Assert.assertEquals("enabled - " + expected.getAlias(), expected.isEnabled(), actual.isEnabled());
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));
}
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();
action.setAlias(alias);
action.setName(name);

View file

@ -16,10 +16,8 @@
*/
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.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
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 java.net.URI;
import java.nio.charset.Charset;
import java.security.Principal;
import java.util.Hashtable;
import java.util.List;
@ -38,9 +39,8 @@ import javax.ws.rs.core.Response;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
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.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ietf.jgss.GSSCredential;
import org.jboss.arquillian.graphene.page.Page;
@ -115,6 +115,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
@Before
@Override
public void beforeAbstractKeycloakTest() throws Exception {
super.beforeAbstractKeycloakTest();
@ -136,6 +137,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
}
@After
@Override
public void afterAbstractKeycloakTest() {
cleanupApacheHttpClient();
@ -347,20 +349,22 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
if (client != null) {
cleanupApacheHttpClient();
}
DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder()
.disableCookieCache(false)
.build();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory);
httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);
if (useSpnego) {
Credentials fake = new Credentials() {
@Override
public String getPassword() {
return null;
}
@Override
public Principal getUserPrincipal() {
return null;
}
@ -409,7 +413,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
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 state = null;
for (NameValuePair pair : pairs) {
@ -444,6 +448,7 @@ public abstract class AbstractKerberosTest extends AbstractAuthTest {
testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);
}
@Override
public RealmResource testRealmResource() {
return adminClient.realm("test");
}

View file

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

View file

@ -18,7 +18,7 @@ package org.keycloak.testsuite.i18n;
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.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
@ -118,7 +118,7 @@ public class LoginPageTest extends AbstractI18NTest {
public void acceptLanguageHeader() {
ProfileAssume.assumeCommunity();
DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build();
CloseableHttpClient httpClient = (CloseableHttpClient) new HttpClientBuilder().build();
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
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 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;
/**

View file

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

View file

@ -17,11 +17,12 @@
package org.keycloak.testsuite.oauth;
import java.io.IOException;
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.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Rule;
@ -90,11 +91,10 @@ public class ClientAuthPostMethodTest extends AbstractKeycloakTest {
private OAuthClient.AccessTokenResponse doAccessTokenRequestPostAuth(String code, String clientSecret) {
CloseableHttpClient client = new DefaultHttpClient();
try {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
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.CODE, code));
parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
@ -116,8 +116,8 @@ public class ClientAuthPostMethodTest extends AbstractKeycloakTest {
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e);
}
} finally {
oauth.closeClient(client);
} catch (IOException e) {
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.junit.Test;
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.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
@ -49,8 +47,6 @@ import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedList;
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.assertFalse;
@ -71,8 +67,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
public void checkIframe() throws IOException {
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) {
String redirectUri = URLEncoder.encode(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8");
HttpGet get = new HttpGet(
@ -80,7 +75,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
"&redirect_uri=" + redirectUri);
CloseableHttpResponse response = client.execute(get);
String s = IOUtils.toString(response.getEntity().getContent());
String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
response.close();
String action = ActionURIUtils.getActionURIFromPageSource(s);
@ -131,7 +126,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode());
s = IOUtils.toString(response.getEntity().getContent());
s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
assertTrue(s.contains("function getCookie()"));
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);
assertEquals(204, response.getStatusLine().getStatusCode());
response.close();
} finally {
client.close();
}
}
@ -177,8 +170,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
ClientResource master = adminClient.realm("master").clients().get(id);
ClientRepresentation rep = master.toRepresentation();
List<String> org = rep.getWebOrigins();
CloseableHttpClient client = HttpClients.createDefault();
try {
try (CloseableHttpClient client = HttpClients.createDefault()) {
rep.setWebOrigins(Collections.singletonList("*"));
master.update(rep);
@ -186,13 +178,12 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
+ "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID
+ "&origin=" + "http://anything"
);
CloseableHttpResponse response = client.execute(get);
assertEquals(204, response.getStatusLine().getStatusCode());
response.close();
try (CloseableHttpResponse response = client.execute(get)) {
assertEquals(204, response.getStatusLine().getStatusCode());
}
} finally {
rep.setWebOrigins(org);
master.update(rep);
client.close();
}
}
@ -200,8 +191,7 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
public void checkIframeCache() throws IOException {
String version = testingClient.server().fetch(new ServerVersion());
CloseableHttpClient client = HttpClients.createDefault();
try {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html");
CloseableHttpResponse response = client.execute(get);
@ -213,8 +203,6 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age"));
} finally {
client.close();
}
}

View file

@ -1,86 +1,38 @@
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.Before;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
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.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.jose.jws.JWSHeader;
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.ModelToRepresentation;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.protocol.oidc.mappers.HardcodedClaim;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
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.ProtocolMapperRepresentation;
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.AssertEvents;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.ClientManager;
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.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 java.io.IOException;
import java.net.URI;
import java.security.MessageDigest;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
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.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

View file

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

View file

@ -19,7 +19,8 @@ package org.keycloak.testsuite.oauth;
import org.apache.http.HttpResponse;
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.Test;
import org.keycloak.OAuth2Constants;
@ -59,7 +60,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
private static String userId2;
private TimeBasedOTP totp = new TimeBasedOTP();
private final TimeBasedOTP totp = new TimeBasedOTP();
@Rule
public AssertEvents events = new AssertEvents(this);
@ -430,8 +431,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
public void grantAccessTokenMissingGrantType() throws Exception {
oauth.clientId("resource-owner");
DefaultHttpClient client = new DefaultHttpClient();
try {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost post = new HttpPost(oauth.getResourceOwnerPasswordCredentialGrantUrl());
OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
@ -439,8 +439,6 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
assertEquals("invalid_request", response.getError());
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.IOException;
import java.nio.charset.Charset;
/**
*
@ -75,7 +76,7 @@ public class TestEventsLogger extends RunListener {
if (driver != null && driver.getPageSource() != null) {
String pageSourceLocation = System.getProperty("page.source.location", "target/failed-tests/page-source/");
FileUtils.writeStringToFile(new File(pageSourceLocation + d.getTestClass().getSimpleName() + "/" + d.getMethodName() + ".html"),
driver.getPageSource());
driver.getPageSource(), Charset.forName("UTF-8"));
}
} catch (IllegalStateException ex) {
Logger.getLogger(TestEventsLogger.class).warn(ex.getMessage());

View file

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