Compare commits

..

23 Commits

Author SHA1 Message Date
bd7413bb48 v1.1.4 pom 2022-02-02 13:34:16 -05:00
75c518801f Merge branch 'develop' into stable 2022-02-02 13:33:47 -05:00
556909f2e9 caching underlying client 2022-02-02 13:33:36 -05:00
6fd42a8daf added minor response trace logging 2022-02-02 13:33:09 -05:00
aea7a0d035 updated jersey version 2021-12-28 14:55:01 -05:00
d3f10e4c00 added trace logging for requests 2021-12-28 14:54:36 -05:00
b3bc04467b v1.1.3 pom 2021-12-21 17:13:26 -05:00
88c8657a34 Merge branch 'develop' into stable 2021-12-21 17:12:58 -05:00
2c4f4f7285 added basic java.time support 2021-12-21 17:12:33 -05:00
28b2478a08 v1.1.2 pom 2021-12-02 16:25:05 -05:00
dc63abc272 Merge branch 'develop' into stable 2021-12-02 16:20:39 -05:00
23c76c4bcf added client enforcement auth filter 2021-12-02 16:20:29 -05:00
dd5d0f504a Merge branch 'develop' into stable 2021-10-27 14:54:54 -04:00
eaa55fa48e javadoc fixes 2021-10-27 14:54:22 -04:00
34d03a91e5 Merge branch 'develop' into stable 2021-09-03 12:42:25 -04:00
d62a941e64 added default null for configs 2021-09-03 12:41:54 -04:00
2584b8d668 v1.1.1 pom 2021-09-03 11:38:52 -04:00
a756b05f6c Merge branch 'develop' into stable 2021-09-03 11:38:22 -04:00
4f9e4eaa4d added javadocs 2021-09-03 11:36:55 -04:00
2e0c98911e added dynamic AuthFilter support for fowarding auth 2021-09-03 10:17:17 -04:00
b91321c6f3 added AuthorizationFilter to segregate 2021-09-03 10:16:00 -04:00
853b4e66cf Merge branch 'develop' into stable 2021-09-01 14:43:43 -04:00
97af0a0698 moved distman from tile 2021-09-01 14:43:36 -04:00
22 changed files with 823 additions and 253 deletions

47
pom.xml
View File

@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8</groupId>
<artifactId>common-rest-api</artifactId>
<version>1.1.0</version>
<version>1.1.4</version>
<name>ReST API Client for Java</name>
<properties>
@@ -14,7 +14,7 @@
<junit.version>5.7.2</junit.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>
</properties>
@@ -34,6 +34,11 @@
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@@ -119,24 +124,36 @@
</dependencies>
</plugin>
<plugin>
<groupId>io.repaint.maven</groupId>
<artifactId>tiles-maven-plugin</artifactId>
<version>2.21</version>
<extensions>true</extensions>
<configuration>
<filtering>true</filtering>
<tiles>
<tile>com.inteligr8:maven-public-deploy-tile:[1.0.0,2.0.0)</tile>
</tiles>
</configuration>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>javadoc</id>
<phase>package</phase>
<goals><goal>jar</goal></goals>
<configuration>
<show>public</show>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>inteligr8-releases</id>
<url>http://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
<id>inteligr8-public</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
</pluginRepository>
</pluginRepositories>
</project>
<distributionManagement>
<repository>
<id>inteligr8-releases</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
</repository>
<snapshotRepository>
<id>inteligr8-snapshots</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-snapshots</url>
</snapshotRepository>
</distributionManagement>
</project>

View File

@@ -1,20 +0,0 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.HttpHeaders;
public class AccessTokenRequestFilter implements ClientRequestFilter {
private final String token;
public AccessTokenRequestFilter(String token) {
this.token = token;
}
@Override
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + this.token);
}
}

View File

@@ -0,0 +1,13 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestFilter;
/**
* This is a marker that allows the developer to segregate, restrict, or limit
* authorization specific implementations of the ClientRequestFilter.
*
* @author brian@inteligr8.com
*/
public interface AuthorizationFilter extends ClientRequestFilter {
}

View File

@@ -4,19 +4,34 @@ import java.io.UnsupportedEncodingException;
import java.util.Base64;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.HttpHeaders;
public class BasicAuthRequestFilter implements ClientRequestFilter {
/**
* This class implements a simple 2-credential (username &amp; password) based
* authorization filter.
*
* @author brian@inteligr8.com
*/
public class BasicAuthorizationFilter implements AuthorizationFilter {
private final String username;
private final String password;
public BasicAuthRequestFilter(String username, String password) {
/**
* @param username A username or access key.
* @param password A password or secret key.
*/
public BasicAuthorizationFilter(String username, String password) {
this.username = username;
this.password = password;
}
/**
* This method applies the 'Authorization' header to the {@link ClientRequestContext}.
*
* @param requestContext A request context.
* @throws UnsupportedEncodingException The 'utf-8' encoding is not supported.
*/
@Override
public void filter(ClientRequestContext requestContext) throws UnsupportedEncodingException {
String userAndPass = this.username + ":" + this.password;

View File

@@ -0,0 +1,37 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.HttpHeaders;
/**
* This class implements a simple long living or proxied token-based
* authorization filter. The token is expected to be acquired outside of the
* purview of this library.
*
* If you have the full authorization header and not just the bearer token, use
* the {@link ForwardingAuthorizationFilter}.
*
* @author brian@inteligr8.com
*/
public class BearerTokenAuthorizationFilter implements AuthorizationFilter {
private final String token;
/**
* @param token A 'Bearer' token.
*/
public BearerTokenAuthorizationFilter(String token) {
this.token = token;
}
/**
* This method applies the 'Authorization' header to the {@link ClientRequestContext}.
*
* @param requestContext A request context.
*/
@Override
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + this.token);
}
}

View File

@@ -1,34 +1,112 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestFilter;
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.JacksonJsonProvider;
/**
* Configured JAX-RS Client & WebTarget
* A class that provides pre-configured JAX-RS Client &amp; WebTarget objects.
*
* @author brian@inteligr8.com
*/
public abstract class Client {
private final Object sync = new Object();
private javax.ws.rs.client.Client client;
protected abstract ClientConfiguration getConfig();
public javax.ws.rs.client.Client getClient() {
ClientRequestFilter authFilter = this.getConfig().getAuthorizationFilter();
/**
* @return A pre-configured JAX-RS client (no URL) with configured authorization.
*/
public final javax.ws.rs.client.Client getClient() {
synchronized (this.sync) {
if (this.client == null)
this.client = this.buildClient(null);
}
return this.client;
}
/**
* @param authFilter A dynamic authorization filter.
* @return A pre-configured JAX-RS client (no URL) with the specified authorization.
*/
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 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()
.register(new JacksonJaxbJsonProvider());
.register(provider)
.register(new LoggingFilter());
if (authFilter == null)
authFilter = this.getConfig().createAuthorizationFilter();
if (authFilter != null)
clientBuilder.register(authFilter);
return clientBuilder.build();
}
public WebTarget getTarget() {
/**
* @return A pre-configured JAX-RS target (client w/ base URL) with configured authorization.
*/
public final WebTarget getTarget() {
return this.getClient()
.target(this.getConfig().getBaseUrl());
}
/**
* @param authFilter A dynamic authorization filter.
* @return A pre-configured JAX-RS target (client w/ base URL) with the specified authorization.
*/
public WebTarget getTarget(AuthorizationFilter authFilter) {
if (authFilter == null) {
return this.getTarget();
} else {
return this.getClient(authFilter)
.target(this.getConfig().getBaseUrl());
}
}
public abstract <T> T getApi(Class<T> apiClass);
/**
* This method retrieves a JAX-RS implementation of the specified API.
*
* @param apiClass A JAX-RS annotation API class.
* @return An instance of the API class.
*/
public final <T> T getApi(Class<T> apiClass) {
return this.getApi(null, apiClass);
}
/**
* This method retrieves a JAX-RS implementation of the specified API with
* the specified authorization.
*
* @param authFilter A dynamic authorization filter.
* @param apiClass A JAX-RS annotation API class.
* @return An instance of the API class.
*/
public abstract <T> T getApi(AuthorizationFilter authFilter, Class<T> apiClass);
}

View File

@@ -2,50 +2,155 @@ package com.inteligr8.rs;
import java.net.URI;
import javax.ws.rs.client.ClientRequestFilter;
/**
* This interface defines the configurable parameters of the clients; primarily
* their default authentication and authorization.
*
* @author brian@inteligr8.com
*/
public interface ClientConfiguration {
/**
* @return The base or root URL of the service.
*/
String getBaseUrl();
String getBasicAuthUsername();
String getBasicAuthPassword();
String getAccessToken();
String getOAuthTokenUrl();
String getOAuthClientId();
String getOAuthClientSecret();
String getOAuthAuthCode();
String getOAuthAuthRedirectUri();
String getOAuthUsername();
String getOAuthPassword();
/**
* @return The username for BASIC authentication.
*/
default String getBasicAuthUsername() {
return null;
}
default ClientRequestFilter getAuthorizationFilter() {
if (this.getAccessToken() != null) {
return new AccessTokenRequestFilter(this.getAccessToken());
/**
* @return The corresponding password for the username in BASIC authentication.
*/
default String getBasicAuthPassword() {
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.
*/
default String getBearerToken() {
return null;
}
/**
* @return The token URL for OAuth authorization.
*/
default String getOAuthTokenUrl() {
return null;
}
/**
* @return The client ID provided by the OAuth IdP administrator.
*/
default String getOAuthClientId() {
return this.getClientId();
}
/**
* @return The corresponding client secret for the client ID provided by the OAuth IdP administrator.
*/
default String getOAuthClientSecret() {
return this.getClientSecret();
}
/**
* @return The authorization code used in the OAuth Authorization Code flow.
*/
default String getOAuthAuthCode() {
return null;
}
/**
* @return The redirect URL used in the OAuth Authorization Code flow.
*/
default String getOAuthAuthRedirectUri() {
return null;
}
/**
* @return The username used in the OAuth Password Grant flow.
*/
default String getOAuthUsername() {
return null;
}
/**
* @return The corresponding password for the username used in the OAuth Password Grant flow.
*/
default String getOAuthPassword() {
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
* available. A configuration element is considered to not be available
* when its value is null. If multiple configurations are specified, the
* filter is selected with the following precedence.
*
* - Bearer
* - OAuth Authorization Code
* - OAuth Password Grant
* - OAuth Client Credential
* - Basic
*
* @return An authorization filter; may be null
*/
default AuthorizationFilter createAuthorizationFilter() {
if (this.getBearerToken() != null) {
return new BearerTokenAuthorizationFilter(this.getBearerToken());
} else if (this.getOAuthTokenUrl() != null) {
if (this.getOAuthAuthCode() != null) {
return new OAuthAuthorizationCodeRequestFilter(this.getOAuthTokenUrl(),
return new OAuthAuthorizationCodeAuthorizationFilter(this.getOAuthTokenUrl(),
this.getOAuthClientId(), this.getOAuthClientSecret(),
this.getOAuthAuthCode(), URI.create(this.getOAuthAuthRedirectUri()));
} else if (this.getOAuthUsername() != null) {
return new OAuthPasswordGrantRequestFilter(this.getOAuthTokenUrl(),
return new OAuthPasswordGrantAuthorizationFilter(this.getOAuthTokenUrl(),
this.getOAuthClientId(), this.getOAuthClientSecret(),
this.getOAuthUsername(), this.getOAuthPassword());
} else {
return new OAuthClientCredentialRequestFilter(this.getOAuthTokenUrl(),
return new OAuthClientCredentialAuthorizationFilter(this.getOAuthTokenUrl(),
this.getOAuthClientId(), this.getOAuthClientSecret());
}
} else if (this.getClientId() != null) {
return new ClientEnforcementAuthorizationFilter(this.getClientId(), this.getClientSecret());
} else if (this.getBasicAuthUsername() != null) {
return new BasicAuthRequestFilter(this.getBasicAuthUsername(), this.getBasicAuthPassword());
return new BasicAuthorizationFilter(this.getBasicAuthUsername(), this.getBasicAuthPassword());
} else {
return null;
}

View File

@@ -1,7 +1,22 @@
package com.inteligr8.rs;
/**
* This interface defines additional configurations specific to the Apache CXF
* JAX-RS library and its nuances.
*
* @author brian@inteligr8.com
*/
public interface ClientCxfConfiguration extends ClientConfiguration {
/**
* Apache CXF uses a global bus configuration where interceptors could
* wreck havoc on your implementation. This method allows you to
* explicitly by-pass the default bus.
*
* See https://cxf.apache.org/docs/bus-configuration.html.
*
* @return true to use the default bus; false otherwise.
*/
default boolean isDefaultBusEnabled() {
return true;
}

View File

@@ -3,7 +3,6 @@ package com.inteligr8.rs;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.RuntimeDelegate;
import org.apache.cxf.BusFactory;
@@ -17,7 +16,10 @@ import org.springframework.beans.factory.InitializingBean;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
/**
* Configured JAX-RS Client & WebTarget & CXF WebClient for CXF
* A class that provides pre-configured JAX-RS Client &amp; WebTarget &amp;
* CXF WebClient objects.
*
* @author brian@inteligr8.com
*/
public abstract class ClientCxfImpl extends Client implements InitializingBean {
@@ -28,6 +30,14 @@ public abstract class ClientCxfImpl extends Client implements InitializingBean {
@Override
public void afterPropertiesSet() {
this.register();
}
/**
* This method registers the Apache CXF library as the default provider for
* the JAX-RS specification.
*/
public void register() {
if (RuntimeDelegate.getInstance() == null) {
this.logger.info("Setting JAX-RS runtime delegate to the CXF library");
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
@@ -42,11 +52,23 @@ public abstract class ClientCxfImpl extends Client implements InitializingBean {
this.logger.info("API Base URL: " + this.getConfig().getBaseUrl());
}
/**
* @return A CXF client (not JAX-RS).
*/
public WebClient getCxfClient() {
return this.getCxfClient(null);
}
/**
* @param authFilter A post-configuration authorization filter.
* @return A CXF client (not JAX-RS).
*/
public WebClient getCxfClient(AuthorizationFilter authFilter) {
List<Object> providersAndFilters = new LinkedList<Object>();
providersAndFilters.add(new JacksonJaxbJsonProvider());
ClientRequestFilter authFilter = this.getConfig().getAuthorizationFilter();
if (authFilter == null)
authFilter = this.getConfig().createAuthorizationFilter();
if (authFilter != null)
providersAndFilters.add(authFilter);
@@ -64,10 +86,18 @@ public abstract class ClientCxfImpl extends Client implements InitializingBean {
return client;
}
/**
* This method retrieves a JAX-RS implementation of the specified API with
* the specified authorization.
*
* @param authFilter A dynamic authorization filter.
* @param apiClass A JAX-RS annotation API class.
* @return An instance of the API class.
*/
@Override
public <T> T getApi(Class<T> apiClass) {
return JAXRSClientFactory.fromClient(this.getCxfClient(), apiClass);
public <T> T getApi(AuthorizationFilter authFilter, Class<T> apiClass) {
return JAXRSClientFactory.fromClient(this.getCxfClient(authFilter), apiClass);
}
}

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,7 +1,19 @@
package com.inteligr8.rs;
/**
* This interface defines additional configurations specific to the Jersey
* JAX-RS library and its nuances.
*
* @author brian@inteligr8.com
*/
public interface ClientJerseyConfiguration extends ClientConfiguration {
/**
* Jersey is automatically strict in its adherence to the ReST API
* specifications. It requires a body to PUT calls by default.
*
* @return true to require body in PUT calls; false to make it optional
*/
default boolean isPutBodyRequired() {
return true;
}

View File

@@ -10,7 +10,10 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
/**
* Configured JAX-RS Client & WebTarget for Jersey
* A class that provides pre-configured JAX-RS Client &amp; WebTarget objects
* for Jersey.
*
* @author brian@inteligr8.com
*/
public abstract class ClientJerseyImpl extends Client implements InitializingBean {
@@ -21,6 +24,14 @@ public abstract class ClientJerseyImpl extends Client implements InitializingBea
@Override
public void afterPropertiesSet() {
this.register();
}
/**
* This method registers the Jersey library as the default provider for the
* JAX-RS specification.
*/
public void register() {
if (RuntimeDelegate.getInstance() == null) {
this.logger.info("Setting JAX-RS runtime delegate to the Jersey library");
RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
@@ -35,9 +46,13 @@ public abstract class ClientJerseyImpl extends Client implements InitializingBea
this.logger.info("API Base URL: " + this.getConfig().getBaseUrl());
}
/**
* @param authFilter A post-configuration authorization filter.
* @return A JAX-RS client.
*/
@Override
public javax.ws.rs.client.Client getClient() {
javax.ws.rs.client.Client client = super.getClient();
public javax.ws.rs.client.Client getClient(AuthorizationFilter authFilter) {
javax.ws.rs.client.Client client = super.getClient(authFilter);
if (!this.getConfig().isPutBodyRequired()) {
// allow PUT operations without body data
@@ -46,10 +61,18 @@ public abstract class ClientJerseyImpl extends Client implements InitializingBea
return client;
}
/**
* This method retrieves a JAX-RS implementation of the specified API with
* the specified authorization.
*
* @param authFilter A dynamic authorization filter.
* @param apiClass A JAX-RS annotation API class.
* @return An instance of the API class.
*/
@Override
public <T> T getApi(Class<T> apiClass) {
return WebResourceFactory.newResource(apiClass, this.getTarget());
public <T> T getApi(AuthorizationFilter authFilter, Class<T> apiClass) {
return WebResourceFactory.newResource(apiClass, this.getTarget(authFilter));
}
}

View File

@@ -0,0 +1,37 @@
package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.HttpHeaders;
/**
* This class implements a proxied or forwarded authorization header based
* authorization filter. The authorization header is expected to be acquired
* outside of the purview of this library.
*
* If you have a bearer token and not the full authorization header, use the
* {@link BearerTokenAuthorizationFilter}.
*
* @author brian@inteligr8.com
*/
public class ForwardingAuthorizationFilter implements AuthorizationFilter {
private final String authorizationHeaderValue;
/**
* @param authorizationHeaderValue A previously used or formulated 'Authorization' header.
*/
public ForwardingAuthorizationFilter(String authorizationHeaderValue) {
this.authorizationHeaderValue = authorizationHeaderValue;
}
/**
* This method applies the 'Authorization' header to the {@link ClientRequestContext}.
*
* @param requestContext A request context.
*/
@Override
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, this.authorizationHeaderValue);
}
}

View File

@@ -0,0 +1,54 @@
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.databind.ObjectMapper;
public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter {
private final Logger loggerRequest = LoggerFactory.getLogger("jaxrs.request");
private final Logger loggerResponse = LoggerFactory.getLogger("jaxrs.response");
private final ObjectMapper om = new ObjectMapper();
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (this.loggerRequest.isTraceEnabled()) {
if (MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())) {
this.loggerRequest.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) {
this.loggerRequest.trace("request: {} {}: {}", requestContext.getMethod(), requestContext.getUri(),
((Form)requestContext.getEntity()).asMap());
} else {
this.loggerRequest.trace("request: {} {}: failed to output form", requestContext.getMethod(), requestContext.getUri());
}
} else if (requestContext.getMediaType() != null) {
this.loggerRequest.trace("request '{}': {} {}", requestContext.getMediaType(), requestContext.getMethod(), requestContext.getUri());
} else {
this.loggerRequest.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

@@ -0,0 +1,70 @@
package com.inteligr8.rs;
import java.net.URI;
import javax.ws.rs.core.Form;
/**
* This class implements the OAuth Authorization Code flow as an authorization
* filter.
*
* @author brian@inteligr8.com
*/
public class OAuthAuthorizationCodeAuthorizationFilter extends OAuthAuthorizationFilter {
private final String code;
private final URI redirectUri;
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param code The authorization code acquired from the OAuth IdP from a user outside the purview of this library.
*/
public OAuthAuthorizationCodeAuthorizationFilter(String tokenUrl, String clientId, String code) {
this(tokenUrl, clientId, null, code);
}
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param code The authorization code acquired from the OAuth IdP from a user outside the purview of this library.
* @param redirectUri The URL for the OAuth IdP to redirect after successful authorization.
*/
public OAuthAuthorizationCodeAuthorizationFilter(String tokenUrl, String clientId, String code, URI redirectUri) {
this(tokenUrl, clientId, null, code, redirectUri);
}
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param clientSecret The passcode provided by the OAuth IdP administrator.
* @param code The authorization code acquired from the OAuth IdP from a user outside the purview of this library.
*/
public OAuthAuthorizationCodeAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String code) {
this(tokenUrl, clientId, clientSecret, code, null);
}
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param clientSecret The passcode provided by the OAuth IdP administrator.
* @param code The authorization code acquired from the OAuth IdP from a user outside the purview of this library.
* @param redirectUri The URL for the OAuth IdP to redirect after successful authorization.
*/
public OAuthAuthorizationCodeAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String code, URI redirectUri) {
super(tokenUrl, clientId, clientSecret);
this.code = code;
this.redirectUri = redirectUri;
}
@Override
protected Form createForm() {
Form form = new Form().param("grant_type", "authorization_code")
.param("code", this.code);
if (this.redirectUri != null)
form.param("redirect_uri", this.redirectUri.toString());
return form;
}
}

View File

@@ -1,40 +0,0 @@
package com.inteligr8.rs;
import java.net.URI;
import javax.ws.rs.core.Form;
public class OAuthAuthorizationCodeRequestFilter extends OAuthRequestFilter {
private final String code;
private final URI redirectUri;
public OAuthAuthorizationCodeRequestFilter(String tokenUrl, String clientId, String code) {
this(tokenUrl, clientId, null, code);
}
public OAuthAuthorizationCodeRequestFilter(String tokenUrl, String clientId, String code, URI redirectUri) {
this(tokenUrl, clientId, null, code, redirectUri);
}
public OAuthAuthorizationCodeRequestFilter(String tokenUrl, String clientId, String clientSecret, String code) {
this(tokenUrl, clientId, clientSecret, code, null);
}
public OAuthAuthorizationCodeRequestFilter(String tokenUrl, String clientId, String clientSecret, String code, URI redirectUri) {
super(tokenUrl, clientId, clientSecret);
this.code = code;
this.redirectUri = redirectUri;
}
@Override
protected Form createForm() {
Form form = new Form().param("grant_type", "authorization_code")
.param("code", this.code);
if (this.redirectUri != null)
form.param("redirect_uri", this.redirectUri.toString());
return form;
}
}

View File

@@ -0,0 +1,130 @@
package com.inteligr8.rs;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
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 com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
/**
* This class is the base for implementations of OAuth authorization flows.
*
* @author brian@inteligr8.com
*/
public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
private final String tokenUrl;
private final String clientId;
private final String clientSecret;
private final String scope;
private String accessToken;
private long expiration;
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) {
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) {
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) {
this.tokenUrl = tokenUrl;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.scope = scope;
}
/**
* This method applies the 'Authorization' header to the {@link ClientRequestContext}.
*
* @param requestContext A request context.
*/
@Override
public void filter(ClientRequestContext requestContext) {
if (this.accessToken == null || System.currentTimeMillis() > this.expiration)
this.requestToken();
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + this.accessToken);
}
/**
* This method manages the acquisition and refreshing of tokens, per the
* standard OAuth process.
*/
private void requestToken() {
Form form;
if (this.refreshToken != null) {
form = this.createRefreshForm();
} else {
form = this.createForm();
}
form.param("client_id", this.clientId);
if (this.clientSecret != null)
form.param("client_secret", this.clientSecret);
if (this.scope != null)
form.param("scope", this.scope);
Entity<Form> entity = Entity.form(form);
WebTarget target = ClientBuilder.newBuilder()
.register(new JacksonJaxbJsonProvider())
.build()
.target(this.tokenUrl);
@SuppressWarnings("unchecked")
Map<String, Object> response = target.request().post(entity, Map.class);
if (response.containsKey("error"))
throw new WebApplicationException((String)response.get("error"), 400);
this.accessToken = (String)response.get("access_token");
this.expiration = System.currentTimeMillis() + ((Number)response.get("expires_in")).longValue() * 1000L;
this.refreshToken = (String)response.get("refresh_token");
}
protected Form createRefreshForm() {
return new Form().param("grant_type", "refresh_token")
.param("refresh_token", this.refreshToken);
}
protected abstract Form createForm();
}

View File

@@ -0,0 +1,27 @@
package com.inteligr8.rs;
import javax.ws.rs.core.Form;
/**
* This class implements the OAuth Client Credential flow as an authorization
* filter.
*
* @author brian@inteligr8.com
*/
public class OAuthClientCredentialAuthorizationFilter extends OAuthAuthorizationFilter {
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param clientSecret The passcode provided by the OAuth IdP administrator.
*/
public OAuthClientCredentialAuthorizationFilter(String tokenUrl, String clientId, String clientSecret) {
super(tokenUrl, clientId, clientSecret);
}
@Override
protected Form createForm() {
return new Form().param("grant_type", "client_credentials");
}
}

View File

@@ -1,16 +0,0 @@
package com.inteligr8.rs;
import javax.ws.rs.core.Form;
public class OAuthClientCredentialRequestFilter extends OAuthRequestFilter {
public OAuthClientCredentialRequestFilter(String tokenUrl, String clientId, String clientSecret) {
super(tokenUrl, clientId, clientSecret);
}
@Override
protected Form createForm() {
return new Form().param("grant_type", "client_credentials");
}
}

View File

@@ -0,0 +1,46 @@
package com.inteligr8.rs;
import javax.ws.rs.core.Form;
/**
* This class implements the OAuth Password Grant flow as an authorization
* filter.
*
* @author brian@inteligr8.com
*/
public class OAuthPasswordGrantAuthorizationFilter extends OAuthAuthorizationFilter {
private final String username;
private final String password;
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param username A username provided by either the OAuth IdP administrator or one of its integrated providers.
* @param password The corresponding password for the username parameter.
*/
public OAuthPasswordGrantAuthorizationFilter(String tokenUrl, String clientId, String username, String password) {
this(tokenUrl, clientId, null, username, password);
}
/**
* @param tokenUrl The URL to the OAuth IdP token service.
* @param clientId The ID provided by the OAuth IdP administrator.
* @param clientSecret The passcode provided by the OAuth IdP administrator.
* @param username A username provided by either the OAuth IdP administrator or one of its integrated providers.
* @param password The corresponding password for the username parameter.
*/
public OAuthPasswordGrantAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String username, String password) {
super(tokenUrl, clientId, clientSecret);
this.username = username;
this.password = password;
}
@Override
protected Form createForm() {
return new Form().param("grant_type", "password")
.param("username", this.username)
.param("password", this.password);
}
}

View File

@@ -1,27 +0,0 @@
package com.inteligr8.rs;
import javax.ws.rs.core.Form;
public class OAuthPasswordGrantRequestFilter extends OAuthRequestFilter {
private final String username;
private final String password;
public OAuthPasswordGrantRequestFilter(String tokenUrl, String clientId, String username, String password) {
this(tokenUrl, clientId, null, username, password);
}
public OAuthPasswordGrantRequestFilter(String tokenUrl, String clientId, String clientSecret, String username, String password) {
super(tokenUrl, clientId, clientSecret);
this.username = username;
this.password = password;
}
@Override
protected Form createForm() {
return new Form().param("grant_type", "password")
.param("username", this.username)
.param("password", this.password);
}
}

View File

@@ -1,85 +0,0 @@
package com.inteligr8.rs;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
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 com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
public abstract class OAuthRequestFilter implements ClientRequestFilter {
private final String tokenUrl;
private final String clientId;
private final String clientSecret;
private final String scope;
private String accessToken;
private long expiration;
private String refreshToken;
public OAuthRequestFilter(String tokenUrl, String clientId) {
this(tokenUrl, clientId, null);
}
public OAuthRequestFilter(String tokenUrl, String clientId, String clientSecret) {
this(tokenUrl, clientId, clientSecret, null);
}
public OAuthRequestFilter(String tokenUrl, String clientId, String clientSecret, String scope) {
this.tokenUrl = tokenUrl;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.scope = scope;
}
@Override
public void filter(ClientRequestContext requestContext) {
if (this.accessToken == null || System.currentTimeMillis() > this.expiration)
this.requestToken();
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + this.accessToken);
}
private void requestToken() {
Form form;
if (this.refreshToken != null) {
form = new Form().param("grant_type", "refresh_token")
.param("refresh_token", this.refreshToken);
} else {
form = this.createForm();
}
form.param("client_id", this.clientId);
if (this.clientSecret != null)
form.param("client_secret", this.clientSecret);
if (this.scope != null)
form.param("scope", this.scope);
Entity<Form> entity = Entity.form(form);
WebTarget target = ClientBuilder.newBuilder()
.register(new JacksonJaxbJsonProvider())
.build()
.target(this.tokenUrl);
@SuppressWarnings("unchecked")
Map<String, Object> response = target.request().post(entity, Map.class);
if (response.containsKey("error"))
throw new WebApplicationException((String)response.get("error"), 400);
this.accessToken = (String)response.get("access_token");
this.expiration = System.currentTimeMillis() + ((Number)response.get("expires_in")).longValue() * 1000L;
this.refreshToken = (String)response.get("refresh_token");
}
protected abstract Form createForm();
}