[KEYCLOAK-11326] - Refactoring to support different versions of resteasy

This commit is contained in:
Pedro Igor 2019-10-03 10:52:53 -03:00 committed by Stian Thorgersen
parent a2e98b57f4
commit f0fb48fb76
16 changed files with 215 additions and 35 deletions

View file

@ -18,7 +18,6 @@
package org.keycloak.examples.authenticator;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.Authenticator;
@ -89,15 +88,15 @@ public class SecretQuestionAuthenticator implements Authenticator {
}
URI uri = context.getUriInfo().getBaseUriBuilder().path("realms").path(context.getRealm().getName()).build();
addCookie("SECRET_QUESTION_ANSWERED", "true",
addCookie(context, "SECRET_QUESTION_ANSWERED", "true",
uri.getRawPath(),
null, null,
maxCookieAge,
false, true);
}
public static void addCookie(String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean httpOnly) {
HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
public void addCookie(AuthenticationFlowContext context, String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean httpOnly) {
HttpResponse response = context.getSession().getContext().getContextObject(HttpResponse.class);
StringBuffer cookieBuf = new StringBuffer();
ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, comment, maxAge, secure, httpOnly);
String cookie = cookieBuf.toString();

View file

@ -17,13 +17,13 @@
package org.keycloak.admin.client.resource;
import org.jboss.resteasy.util.Base64;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
import org.keycloak.common.util.Base64;
/**
* @author rodrigo.sasaki@icarros.com.br
*/
@ -40,7 +40,7 @@ public class BasicAuthFilter implements ClientRequestFilter {
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
String pair = username + ":" + password;
String authHeader = "Basic " + new String(Base64.encodeBytes(pair.getBytes()));
String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
}

20
pom.xml
View file

@ -78,6 +78,7 @@
<jboss.spec.javax.servlet.jsp.jboss-jsp-api_2.3_spec.version>1.0.3.Final</jboss.spec.javax.servlet.jsp.jboss-jsp-api_2.3_spec.version>
<log4j.version>1.2.17</log4j.version>
<resteasy.version>3.7.0.Final</resteasy.version>
<resteasy4.version>4.3.1.Final</resteasy4.version>
<resteasy.undertow.version>3.7.0.Final</resteasy.undertow.version>
<owasp.html.sanitizer.version>20180219.1</owasp.html.sanitizer.version>
<slf4j-api.version>1.7.22</slf4j-api.version>
@ -314,6 +315,25 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-core</artifactId>
<version>${resteasy4.version}</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>

View file

@ -113,6 +113,11 @@
<artifactId>resteasy-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_2.1_spec</artifactId>

View file

@ -0,0 +1,156 @@
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.common.util;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.ResteasyContext;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
/**
* <p>Provides a layer of indirection to abstract invocations to Resteasy internal APIs. Making also possible to use different
* versions of Resteasy (e.g.: v3 and v4) depending on the stack that the server is running.
*
* <p>The methods herein provided are basically related with accessing context data from Resteasy, which changed in latest versions of Resteasy.
*
* <p>It is important to use this class when access to context data is necessary in order to avoid incompatibilities with future
* versions of Resteasy.
*
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public final class Resteasy {
private static final BiConsumer<Class, Object> PUSH_CONTEXT;
private static final BiConsumer<Class, Object> PUSH_DEFAULT_OBJECT;
private static final Function<Class, Object> PULL_CONTEXT;
private static final Runnable CLEAR_CONTEXT;
static {
if (isRestEasy4()) {
PUSH_CONTEXT = new BiConsumer<Class, Object>() {
@Override
public void accept(Class p1, Object p2) {
ResteasyContext.pushContext(p1, p2);
}
};
PUSH_DEFAULT_OBJECT = new BiConsumer<Class, Object>() {
@Override
public void accept(Class p1, Object p2) {
ResteasyContext.getContextData(org.jboss.resteasy.spi.Dispatcher.class).getDefaultContextObjects()
.put(p1, p2);
}
};
PULL_CONTEXT = new Function<Class, Object>() {
@Override
public Object apply(Class p1) {
return ResteasyContext.getContextData(p1);
}
};
CLEAR_CONTEXT = new Runnable() {
@Override
public void run() {
ResteasyContext.clearContextData();
}
};
} else {
PUSH_CONTEXT = new BiConsumer<Class, Object>() {
@Override
public void accept(Class p1, Object p2) {
ResteasyProviderFactory.getInstance().pushContext(p1, p2);
}
};
PUSH_DEFAULT_OBJECT = new BiConsumer<Class, Object>() {
@Override
public void accept(Class p1, Object p2) {
ResteasyProviderFactory.getInstance().getContextData(Dispatcher.class).getDefaultContextObjects()
.put(p1, p2);
}
};
PULL_CONTEXT = new Function<Class, Object>() {
@Override
public Object apply(Class p1) {
return ResteasyProviderFactory.getInstance().getContextData(p1);
}
};
CLEAR_CONTEXT = new Runnable() {
@Override
public void run() {
ResteasyProviderFactory.getInstance().clearContextData();
}
};
}
}
/**
* Push the given {@code instance} with type/key {@code type} to the Resteasy context associated with the current thread.
*
* @param type the type/key to associate the {@code instance} with
* @param instance the instance
*/
public static void pushContext(Class type, Object instance) {
PUSH_CONTEXT.accept(type, instance);
}
/**
* Lookup the instance associated with the given type/key {@code type} from the Resteasy context associated with the current thread.
*
* @param type the type/key to lookup
* @return the instance associated with the given {@code type} or null if non-existent.
*/
public static <R> R getContextData(Class<R> type) {
return (R) PULL_CONTEXT.apply(type);
}
/**
* Clear the Resteasy context associated with the current thread.
*/
public static void clearContextData() {
CLEAR_CONTEXT.run();
}
/**
* Push the given {@code instance} with type/key {@code type} to the Resteasy global context.
*
* @param type the type/key to associate the {@code instance} with
* @param instance the instance
*/
public static void pushDefaultContextObject(Class type, Object instance) {
PUSH_DEFAULT_OBJECT.accept(type, instance);
}
private static boolean isRestEasy4() {
try {
return Class.forName("org.jboss.resteasy.core.ResteasyContext") != null;
} catch (ClassNotFoundException ignore) {
return false;
}
}
/**
* Only necessary because keycloak-common is constrained to JDK 1.7.
*/
private interface BiConsumer<T, S> {
void accept(T p1, S p2);
}
/**
* Only necessary because keycloak-common is constrained to JDK 1.7.
*/
private interface Function<T, R> {
R apply(T p1);
}
}

View file

@ -17,8 +17,8 @@
package org.keycloak.services;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.util.Resteasy;
import org.keycloak.locale.LocaleSelectorProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakContext;
@ -84,7 +84,7 @@ public class DefaultKeycloakContext implements KeycloakContext {
@Override
public <T> T getContextObject(Class<T> clazz) {
return ResteasyProviderFactory.getContextData(clazz);
return Resteasy.getContextData(clazz);
}
@Override

View file

@ -5,6 +5,7 @@ import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.Config;
import org.keycloak.common.util.Resteasy;
import org.keycloak.forms.login.freemarker.model.UrlBean;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransaction;
@ -55,7 +56,7 @@ public class KeycloakErrorHandler implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable throwable) {
KeycloakTransaction tx = ResteasyProviderFactory.getContextData(KeycloakTransaction.class);
KeycloakTransaction tx = Resteasy.getContextData(KeycloakTransaction.class);
tx.setRollbackOnly();
int statusCode = getStatusCode(throwable);

View file

@ -19,6 +19,7 @@ package org.keycloak.services.filters;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.util.Resteasy;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.KeycloakTransaction;
@ -52,7 +53,7 @@ public class KeycloakSessionServletFilter implements Filter {
KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
KeycloakSession session = sessionFactory.create();
ResteasyProviderFactory.pushContext(KeycloakSession.class, session);
Resteasy.pushContext(KeycloakSession.class, session);
ClientConnection connection = new ClientConnection() {
@Override
public String getRemoteAddr() {
@ -80,10 +81,10 @@ public class KeycloakSessionServletFilter implements Filter {
}
};
session.getContext().setConnection(connection);
ResteasyProviderFactory.pushContext(ClientConnection.class, connection);
Resteasy.pushContext(ClientConnection.class, connection);
KeycloakTransaction tx = session.getTransactionManager();
ResteasyProviderFactory.pushContext(KeycloakTransaction.class, tx);
Resteasy.pushContext(KeycloakTransaction.class, tx);
tx.begin();
try {
@ -128,7 +129,7 @@ public class KeycloakSessionServletFilter implements Filter {
}
session.close();
ResteasyProviderFactory.clearContextData();
Resteasy.clearContextData();
}
@Override

View file

@ -20,7 +20,7 @@
package org.keycloak.services.filters;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.common.util.Resteasy;
import org.keycloak.models.KeycloakTransaction;
import javax.ws.rs.container.ContainerRequestContext;
@ -35,7 +35,7 @@ public class KeycloakTransactionCommitter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
KeycloakTransaction tx = ResteasyProviderFactory.getContextData(KeycloakTransaction.class);
KeycloakTransaction tx = Resteasy.getContextData(KeycloakTransaction.class);
if (tx != null && tx.isActive()) {
if (tx.getRollbackOnly()) {
tx.rollback();

View file

@ -22,8 +22,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.Config;
import org.keycloak.common.util.Resteasy;
import org.keycloak.common.util.SystemEnvProperties;
import org.keycloak.exportimport.ExportImportManager;
import org.keycloak.migration.MigrationModelManager;
@ -106,8 +106,10 @@ public class KeycloakApplication extends Application {
protected KeycloakSessionFactory sessionFactory;
protected String contextPath;
public KeycloakApplication(@Context ServletContext context, @Context Dispatcher dispatcher) {
public KeycloakApplication() {
try {
ServletContext context = Resteasy.getContextData(ServletContext.class);
if ("true".equals(context.getInitParameter(KEYCLOAK_EMBEDDED))) {
embedded = true;
}
@ -117,8 +119,8 @@ public class KeycloakApplication extends Application {
this.contextPath = context.getContextPath();
this.sessionFactory = createSessionFactory();
dispatcher.getDefaultContextObjects().put(KeycloakApplication.class, this);
ResteasyProviderFactory.pushContext(KeycloakApplication.class, this); // for injection
Resteasy.pushDefaultContextObject(KeycloakApplication.class, this);
Resteasy.pushContext(KeycloakApplication.class, this); // for injection
context.setAttribute(KeycloakSessionFactory.class.getName(), this.sessionFactory);
singletons.add(new RobotsResource());

View file

@ -18,8 +18,8 @@
package org.keycloak.services.util;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.Config;
import org.keycloak.common.util.Resteasy;
import javax.ws.rs.core.CacheControl;
@ -29,7 +29,7 @@ import javax.ws.rs.core.CacheControl;
public class CacheControlUtil {
public static void noBackButtonCacheControlHeader() {
HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
HttpResponse response = Resteasy.getContextData(HttpResponse.class);
response.getOutputHeaders().putSingle("Cache-Control", "no-store, must-revalidate, max-age=0");
}

View file

@ -25,7 +25,7 @@ import java.util.stream.Collectors;
import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.common.util.Resteasy;
import org.keycloak.common.util.ServerCookie;
import javax.ws.rs.core.Cookie;
@ -53,7 +53,7 @@ public class CookieHelper {
* @param httpOnly
*/
public static void addCookie(String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean httpOnly) {
HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
HttpResponse response = Resteasy.getContextData(HttpResponse.class);
StringBuffer cookieBuf = new StringBuffer();
ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, comment, maxAge, secure, httpOnly);
String cookie = cookieBuf.toString();
@ -62,7 +62,7 @@ public class CookieHelper {
public static Set<String> getCookieValue(String name) {
HttpHeaders headers = ResteasyProviderFactory.getContextData(HttpHeaders.class);
HttpHeaders headers = Resteasy.getContextData(HttpHeaders.class);
Set<String> cookiesVal = new HashSet<>();

View file

@ -18,7 +18,7 @@
package org.keycloak.services.util;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.common.util.Resteasy;
/**
* IE requires P3P header to allow loading cookies from iframes when domain differs from main page (see KEYCLOAK-2828 for more details)
@ -28,7 +28,7 @@ import org.jboss.resteasy.spi.ResteasyProviderFactory;
public class P3PHelper {
public static void addP3PHeader() {
HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class);
HttpResponse response = Resteasy.getContextData(HttpResponse.class);
response.getOutputHeaders().putSingle("P3P", "CP=\"This is not a P3P policy!\"");
}

View file

@ -16,7 +16,6 @@
*/
package org.keycloak.social.google;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.OAuth2Constants;
import org.keycloak.broker.oidc.OIDCIdentityProvider;
import org.keycloak.broker.oidc.OIDCIdentityProviderConfig;
@ -63,7 +62,7 @@ public class GoogleIdentityProvider extends OIDCIdentityProvider implements Soci
protected String getUserInfoUrl() {
String uri = super.getUserInfoUrl();
if (((GoogleIdentityProviderConfig)getConfig()).isUserIp()) {
ClientConnection connection = ResteasyProviderFactory.getContextData(ClientConnection.class);
ClientConnection connection = session.getContext().getConnection();
if (connection != null) {
uri = KeycloakUriBuilder.fromUri(super.getUserInfoUrl()).queryParam("userIp", connection.getRemoteAddr()).build().toString();
}

View file

@ -133,7 +133,7 @@ public class TestApplicationResourceProvider implements RealmResourceProvider {
sb.append("<html><head><title>" + title + "</title></head><body>");
sb.append("<b>Form parameters: </b><br>");
HttpRequest request = ResteasyProviderFactory.getContextData(HttpRequest.class);
HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
MultivaluedMap<String, String> formParams = request.getDecodedFormParameters();
for (String paramName : formParams.keySet()) {
sb.append(paramName).append(": ").append("<span id=\"")

View file

@ -17,9 +17,7 @@
package org.keycloak.testsuite.rest;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.KeycloakSession;
@ -36,7 +34,6 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@ -130,7 +127,7 @@ public class TestSamlApplicationResourceProvider implements RealmResourceProvide
sb.append("<html><head><title>" + title + "</title></head><body>");
sb.append("<b>Form parameters: </b><br>");
HttpRequest request = ResteasyProviderFactory.getContextData(HttpRequest.class);
HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
MultivaluedMap<String, String> formParams = request.getDecodedFormParameters();
for (String paramName : formParams.keySet()) {
sb.append(paramName).append(": ").append("<span id=\"").append(paramName).append("\">").append(formParams.getFirst(paramName)).append("</span><br>");