Compare commits

...

10 Commits
v1.1.1 ... v1.x

12 changed files with 324 additions and 25 deletions

12
pom.xml
View File

@@ -14,7 +14,7 @@
<junit.version>5.7.2</junit.version> <junit.version>5.7.2</junit.version>
<spring.version>5.2.14.RELEASE</spring.version> <spring.version>5.2.14.RELEASE</spring.version>
<jersey.version>2.34</jersey.version> <jersey.version>2.35</jersey.version>
<cxf.version>3.3.2</cxf.version> <cxf.version>3.3.2</cxf.version>
</properties> </properties>
@@ -34,6 +34,16 @@
<artifactId>jackson-jaxrs-json-provider</artifactId> <artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.12.2</version> <version>2.12.2</version>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>

View File

@@ -1,7 +1,5 @@
package com.inteligr8.rs; package com.inteligr8.rs;
import java.io.UnsupportedEncodingException;
import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.HttpHeaders;
@@ -30,7 +28,6 @@ public class BearerTokenAuthorizationFilter implements AuthorizationFilter {
* This method applies the 'Authorization' header to the {@link ClientRequestContext}. * This method applies the 'Authorization' header to the {@link ClientRequestContext}.
* *
* @param requestContext A request context. * @param requestContext A request context.
* @throws UnsupportedEncodingException The 'utf-8' encoding is not supported.
*/ */
@Override @Override
public void filter(ClientRequestContext requestContext) { public void filter(ClientRequestContext requestContext) {

View File

@@ -3,7 +3,10 @@ package com.inteligr8.rs;
import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget; import javax.ws.rs.client.WebTarget;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
/** /**
* A class that provides pre-configured JAX-RS Client &amp; WebTarget objects. * A class that provides pre-configured JAX-RS Client &amp; WebTarget objects.
@@ -12,13 +15,21 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
*/ */
public abstract class Client { public abstract class Client {
private final Object sync = new Object();
private javax.ws.rs.client.Client client;
protected abstract ClientConfiguration getConfig(); protected abstract ClientConfiguration getConfig();
/** /**
* @return A pre-configured JAX-RS client (no URL) with configured authorization. * @return A pre-configured JAX-RS client (no URL) with configured authorization.
*/ */
public final javax.ws.rs.client.Client getClient() { public final javax.ws.rs.client.Client getClient() {
return this.getClient(null); synchronized (this.sync) {
if (this.client == null)
this.client = this.buildClient((AuthorizationFilter)null);
}
return this.client;
} }
/** /**
@@ -26,22 +37,48 @@ public abstract class Client {
* @return A pre-configured JAX-RS client (no URL) with the specified authorization. * @return A pre-configured JAX-RS client (no URL) with the specified authorization.
*/ */
public javax.ws.rs.client.Client getClient(AuthorizationFilter authFilter) { public javax.ws.rs.client.Client getClient(AuthorizationFilter authFilter) {
if (authFilter == null) {
return this.getClient();
} else {
return this.buildClient(authFilter);
}
}
/**
* @param authFilter A dynamic authorization filter.
* @return A pre-configured JAX-RS client (no URL) with the specified authorization.
*/
public final javax.ws.rs.client.Client buildClient(AuthorizationFilter authFilter) {
JacksonJsonProvider provider = new JacksonJaxbJsonProvider();
if (this.getConfig().isWrapRootValueEnabled())
provider.enable(SerializationFeature.WRAP_ROOT_VALUE);
if (this.getConfig().isUnwrapRootValueEnabled())
provider.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
ClientBuilder clientBuilder = ClientBuilder.newBuilder() ClientBuilder clientBuilder = ClientBuilder.newBuilder()
.register(new JacksonJaxbJsonProvider()); .register(provider)
.register(new LoggingFilter());
if (authFilter == null) if (authFilter == null)
authFilter = this.getConfig().createAuthorizationFilter(); authFilter = this.getConfig().createAuthorizationFilter();
if (authFilter != null) if (authFilter != null)
clientBuilder.register(authFilter); clientBuilder.register(authFilter);
this.buildClient(clientBuilder);
return clientBuilder.build(); return clientBuilder.build();
} }
public void buildClient(ClientBuilder clientBuilder) {
// for extension purposes
}
/** /**
* @return A pre-configured JAX-RS target (client w/ base URL) with configured authorization. * @return A pre-configured JAX-RS target (client w/ base URL) with configured authorization.
*/ */
public final WebTarget getTarget() { public final WebTarget getTarget() {
return this.getTarget(null); return this.getClient()
.target(this.getConfig().getBaseUrl());
} }
/** /**
@@ -49,8 +86,12 @@ public abstract class Client {
* @return A pre-configured JAX-RS target (client w/ base URL) with the specified authorization. * @return A pre-configured JAX-RS target (client w/ base URL) with the specified authorization.
*/ */
public WebTarget getTarget(AuthorizationFilter authFilter) { public WebTarget getTarget(AuthorizationFilter authFilter) {
return this.getClient(authFilter) if (authFilter == null) {
.target(this.getConfig().getBaseUrl()); return this.getTarget();
} else {
return this.getClient(authFilter)
.target(this.getConfig().getBaseUrl());
}
} }
/** /**

View File

@@ -29,6 +29,20 @@ public interface ClientConfiguration {
return null; return null;
} }
/**
* @return The client ID for Client Enforcement authentication.
*/
default String getClientId() {
return null;
}
/**
* @return The corresponding client secret for the client ID in Client Enforcement authentication.
*/
default String getClientSecret() {
return null;
}
/** /**
* @return The token for BEARER authorization. * @return The token for BEARER authorization.
*/ */
@@ -47,14 +61,14 @@ public interface ClientConfiguration {
* @return The client ID provided by the OAuth IdP administrator. * @return The client ID provided by the OAuth IdP administrator.
*/ */
default String getOAuthClientId() { default String getOAuthClientId() {
return null; return this.getClientId();
} }
/** /**
* @return The corresponding client secret for the client ID provided by the OAuth IdP administrator. * @return The corresponding client secret for the client ID provided by the OAuth IdP administrator.
*/ */
default String getOAuthClientSecret() { default String getOAuthClientSecret() {
return null; return this.getClientSecret();
} }
/** /**
@@ -84,6 +98,24 @@ public interface ClientConfiguration {
default String getOAuthPassword() { default String getOAuthPassword() {
return null; return null;
} }
/**
* @return true to enable Jackson UNWRAP_ROOT_VALUE feature; false otherwise.
*/
default boolean isUnwrapRootValueEnabled() {
return false;
}
/**
* @return true to enable Jackson WRAP_ROOT_VALUE feature; false otherwise.
*/
default boolean isWrapRootValueEnabled() {
return false;
}
/** /**
* This method creates an authorization filter based on the configuration * This method creates an authorization filter based on the configuration
@@ -115,6 +147,8 @@ public interface ClientConfiguration {
return new OAuthClientCredentialAuthorizationFilter(this.getOAuthTokenUrl(), return new OAuthClientCredentialAuthorizationFilter(this.getOAuthTokenUrl(),
this.getOAuthClientId(), this.getOAuthClientSecret()); this.getOAuthClientId(), this.getOAuthClientSecret());
} }
} else if (this.getClientId() != null) {
return new ClientEnforcementAuthorizationFilter(this.getClientId(), this.getClientSecret());
} else if (this.getBasicAuthUsername() != null) { } else if (this.getBasicAuthUsername() != null) {
return new BasicAuthorizationFilter(this.getBasicAuthUsername(), this.getBasicAuthPassword()); return new BasicAuthorizationFilter(this.getBasicAuthUsername(), this.getBasicAuthPassword());
} else { } else {

View File

@@ -13,7 +13,7 @@ public interface ClientCxfConfiguration extends ClientConfiguration {
* wreck havoc on your implementation. This method allows you to * wreck havoc on your implementation. This method allows you to
* explicitly by-pass the default bus. * explicitly by-pass the default bus.
* *
* @see https://cxf.apache.org/docs/bus-configuration.html * See https://cxf.apache.org/docs/bus-configuration.html.
* *
* @return true to use the default bus; false otherwise. * @return true to use the default bus; false otherwise.
*/ */

View File

@@ -66,11 +66,15 @@ public abstract class ClientCxfImpl extends Client implements InitializingBean {
public WebClient getCxfClient(AuthorizationFilter authFilter) { public WebClient getCxfClient(AuthorizationFilter authFilter) {
List<Object> providersAndFilters = new LinkedList<Object>(); List<Object> providersAndFilters = new LinkedList<Object>();
providersAndFilters.add(new JacksonJaxbJsonProvider()); providersAndFilters.add(new JacksonJaxbJsonProvider());
providersAndFilters.add(new CxfLoggingFilter());
providersAndFilters.add(new CxfMultipartProvider());
if (authFilter == null) if (authFilter == null)
authFilter = this.getConfig().createAuthorizationFilter(); authFilter = this.getConfig().createAuthorizationFilter();
if (authFilter != null) if (authFilter != null)
providersAndFilters.add(authFilter); providersAndFilters.add(authFilter);
this.addProvidersAndFilters(providersAndFilters);
// we can't use JAXRSClientFactory with a JAXRS client (duh!) // we can't use JAXRSClientFactory with a JAXRS client (duh!)
// so we need to create a CXF client // so we need to create a CXF client
@@ -86,6 +90,10 @@ public abstract class ClientCxfImpl extends Client implements InitializingBean {
return client; return client;
} }
public void addProvidersAndFilters(List<Object> providersAndFilters) {
// for extension purposes
}
/** /**
* This method retrieves a JAX-RS implementation of the specified API with * This method retrieves a JAX-RS implementation of the specified API with

View File

@@ -0,0 +1,49 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestContext;
/**
* This class is the base for implementations of client authorization similar
* to OAuth-based flows.
*
* @author brian@inteligr8.com
*/
public class ClientEnforcementAuthorizationFilter implements AuthorizationFilter {
private final String clientId;
private final String clientSecret;
/**
* This constructor creates a client authorization filter using a client ID
* registered with the endpoint.
*
* @param clientId An endpoint provided client ID.
*/
public ClientEnforcementAuthorizationFilter(String clientId) {
this(clientId, null);
}
/**
* This constructor creates a client authorization filter using a client ID
* registered with the endpoint, and the corresponding client secret.
*
* @param clientId An endpoint provided client ID.
* @param clientSecret A secret corresponding to the client ID.
*/
public ClientEnforcementAuthorizationFilter(String clientId, String clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/**
* This method applies the client headers to the {@link ClientRequestContext}.
*
* @param requestContext A request context.
*/
@Override
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().add("client_id", this.clientId);
requestContext.getHeaders().add("client_secret", this.clientSecret);
}
}

View File

@@ -1,10 +1,12 @@
package com.inteligr8.rs; package com.inteligr8.rs;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.ext.RuntimeDelegate; import javax.ws.rs.ext.RuntimeDelegate;
import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.proxy.WebResourceFactory; import org.glassfish.jersey.client.proxy.WebResourceFactory;
import org.glassfish.jersey.internal.RuntimeDelegateImpl; import org.glassfish.jersey.internal.RuntimeDelegateImpl;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
@@ -26,7 +28,11 @@ public abstract class ClientJerseyImpl extends Client implements InitializingBea
public void afterPropertiesSet() { public void afterPropertiesSet() {
this.register(); this.register();
} }
/**
* This method registers the Jersey library as the default provider for the
* JAX-RS specification.
*/
public void register() { public void register() {
if (RuntimeDelegate.getInstance() == null) { if (RuntimeDelegate.getInstance() == null) {
this.logger.info("Setting JAX-RS runtime delegate to the Jersey library"); this.logger.info("Setting JAX-RS runtime delegate to the Jersey library");
@@ -42,20 +48,14 @@ public abstract class ClientJerseyImpl extends Client implements InitializingBea
this.logger.info("API Base URL: " + this.getConfig().getBaseUrl()); this.logger.info("API Base URL: " + this.getConfig().getBaseUrl());
} }
/**
* @param authFilter A post-configuration authorization filter.
* @return A JAX-RS client.
*/
@Override @Override
public javax.ws.rs.client.Client getClient(AuthorizationFilter authFilter) { public void buildClient(ClientBuilder clientBuilder) {
javax.ws.rs.client.Client client = super.getClient(authFilter); clientBuilder.register(MultiPartFeature.class);
if (!this.getConfig().isPutBodyRequired()) { if (!this.getConfig().isPutBodyRequired()) {
// allow PUT operations without body data // allow PUT operations without body data
client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); clientBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
} }
return client;
} }
/** /**

View File

@@ -0,0 +1,30 @@
package com.inteligr8.rs;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.slf4j.Logger;
public class CxfLoggingFilter extends LoggingFilter {
@Override
protected void logUnhandledRequest(ClientRequestContext requestContext, Logger logger) throws IOException {
if (MediaType.MULTIPART_FORM_DATA_TYPE.equals(requestContext.getMediaType())) {
if (requestContext.getEntity() instanceof MultipartBody) {
List<String> attIds = new LinkedList<>();
for (Attachment att : ((MultipartBody)requestContext.getEntity()).getAllAttachments())
attIds.add(att.getContentId());
logger.trace("request: {} {}: {}", requestContext.getMethod(), requestContext.getUri(), attIds);
} else {
logger.trace("request: {} {}: failed to output form", requestContext.getMethod(), requestContext.getUri());
}
}
}
}

View File

@@ -0,0 +1,29 @@
package com.inteligr8.rs;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.apache.cxf.jaxrs.provider.MultipartProvider;
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.MULTIPART_FORM_DATA)
@Provider
public class CxfMultipartProvider extends MultipartProvider {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MultipartBody.class.isAssignableFrom(type) || this.isReadable(type, genericType, annotations, mediaType);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MultipartBody.class.isAssignableFrom(type) || this.isWriteable(type, genericType, annotations, mediaType);
}
}

View File

@@ -0,0 +1,65 @@
package com.inteligr8.rs;
import java.io.IOException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter {
private final Logger loggerRequest = LoggerFactory.getLogger("jaxrs.request");
private final Logger loggerResponse = LoggerFactory.getLogger("jaxrs.response");
protected final ObjectMapper om = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (this.loggerRequest.isTraceEnabled())
this.logAnyRequest(requestContext, this.loggerRequest);
}
protected void logAnyRequest(ClientRequestContext requestContext, Logger logger) throws IOException {
if (MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())) {
logger.trace("request: {} {}: {}", requestContext.getMethod(), requestContext.getUri(),
this.om.writeValueAsString(requestContext.getEntity()));
} else if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.equals(requestContext.getMediaType())) {
if (requestContext.getEntity() instanceof Form) {
logger.trace("request: {} {}: {}", requestContext.getMethod(), requestContext.getUri(),
((Form)requestContext.getEntity()).asMap());
} else {
this.loggerRequest.trace("request: {} {}: failed to output form", requestContext.getMethod(), requestContext.getUri());
}
} else {
this.logUnhandledRequest(requestContext, logger);
}
}
protected void logUnhandledRequest(ClientRequestContext requestContext, Logger logger) throws IOException {
if (requestContext.getMediaType() != null) {
logger.trace("request '{}': {} {}", requestContext.getMediaType(), requestContext.getMethod(), requestContext.getUri());
} else {
logger.trace("request: {} {}", requestContext.getMethod(), requestContext.getUri());
}
}
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
if (this.loggerResponse.isTraceEnabled()) {
this.loggerResponse.trace("response: {} ", this.om.writeValueAsString(responseContext.getStatus()));
// WARN body is stream, which would need to be replaced after read
this.loggerResponse.warn("response: NOT YET SUPPORTED");
}
}
}

View File

@@ -27,14 +27,42 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
private long expiration; private long expiration;
private String refreshToken; private String refreshToken;
/**
* This constructor creates an OAuth-based authorization filter using the
* OAuth identity provider token URL and a client ID registered with the
* same OAuth identity provider.
*
* @param tokenUrl An OAuth identity provider token URL.
* @param clientId An OAuth identity provider client ID.
*/
public OAuthAuthorizationFilter(String tokenUrl, String clientId) { public OAuthAuthorizationFilter(String tokenUrl, String clientId) {
this(tokenUrl, clientId, null); this(tokenUrl, clientId, null);
} }
/**
* This constructor creates an OAuth-based authorization filter using the
* OAuth identity provider token URL, client ID registered with the
* same OAuth identity provider, and the corresponding client secret.
*
* @param tokenUrl An OAuth identity provider token URL.
* @param clientId An OAuth identity provider client ID.
* @param clientSecret A secret corresponding to the client ID.
*/
public OAuthAuthorizationFilter(String tokenUrl, String clientId, String clientSecret) { public OAuthAuthorizationFilter(String tokenUrl, String clientId, String clientSecret) {
this(tokenUrl, clientId, clientSecret, null); this(tokenUrl, clientId, clientSecret, null);
} }
/**
* This constructor creates an OAuth-based authorization filter using the
* OAuth identity provider token URL, client ID registered with the
* same OAuth identity provider, the corresponding client secret, and OAuth
* scope.
*
* @param tokenUrl An OAuth identity provider token URL.
* @param clientId An OAuth identity provider client ID.
* @param clientSecret A secret corresponding to the client ID.
* @param scope An OAuth scope.
*/
public OAuthAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String scope) { public OAuthAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String scope) {
this.tokenUrl = tokenUrl; this.tokenUrl = tokenUrl;
this.clientId = clientId; this.clientId = clientId;
@@ -73,6 +101,7 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
form.param("client_secret", this.clientSecret); form.param("client_secret", this.clientSecret);
if (this.scope != null) if (this.scope != null)
form.param("scope", this.scope); form.param("scope", this.scope);
this.extendRefreshTokenForm(form);
Entity<Form> entity = Entity.form(form); Entity<Form> entity = Entity.form(form);
@@ -90,6 +119,7 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
this.accessToken = (String)response.get("access_token"); this.accessToken = (String)response.get("access_token");
this.expiration = System.currentTimeMillis() + ((Number)response.get("expires_in")).longValue() * 1000L; this.expiration = System.currentTimeMillis() + ((Number)response.get("expires_in")).longValue() * 1000L;
this.refreshToken = (String)response.get("refresh_token"); this.refreshToken = (String)response.get("refresh_token");
this.extendRefreshTokenResponse(response);
} }
protected Form createRefreshForm() { protected Form createRefreshForm() {
@@ -98,5 +128,11 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
} }
protected abstract Form createForm(); protected abstract Form createForm();
protected void extendRefreshTokenForm(Form form) {
}
protected void extendRefreshTokenResponse(Map<String, Object> response) {
}
} }