Compare commits

...

12 Commits

11 changed files with 274 additions and 46 deletions

10
pom.xml
View File

@@ -49,6 +49,11 @@
</properties>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
@@ -69,6 +74,11 @@
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>

View File

@@ -20,6 +20,8 @@ import java.util.Base64;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.lang3.StringUtils;
/**
* This class implements a simple 2-credential (username &amp; password) based
* authorization filter.
@@ -36,8 +38,8 @@ public class BasicAuthorizationFilter implements AuthorizationFilter {
* @param password A password or secret key.
*/
public BasicAuthorizationFilter(String username, String password) {
this.username = username;
this.password = password;
this.username = StringUtils.trimToNull(username);
this.password = StringUtils.trimToNull(password);
}
/**

View File

@@ -14,13 +14,16 @@
*/
package com.inteligr8.rs;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
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.
@@ -66,8 +69,13 @@ public abstract class Client {
* @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();
ObjectMapper om = new ObjectMapper();
om.registerModules(new JavaTimeModule());
this.getConfig().configureJacksonMapper(om);
JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(om, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
this.getConfig().configureJacksonProvider(provider);
if (this.getConfig().isWrapRootValueEnabled())
provider.enable(SerializationFeature.WRAP_ROOT_VALUE);
if (this.getConfig().isUnwrapRootValueEnabled())
@@ -76,22 +84,28 @@ public abstract class Client {
ClientBuilder clientBuilder = ClientBuilder.newBuilder()
.register(provider)
.register(new LoggingFilter());
if (this.getConfig().getConnectTimeoutInMillis() != null)
clientBuilder.connectTimeout(this.getConfig().getConnectTimeoutInMillis(), TimeUnit.MILLISECONDS);
if (this.getConfig().getResponseTimeoutInMillis() != null)
clientBuilder.readTimeout(this.getConfig().getResponseTimeoutInMillis(), TimeUnit.MILLISECONDS);
if (authFilter == null)
authFilter = this.getConfig().createAuthorizationFilter();
if (authFilter != null)
clientBuilder.register(authFilter);
this.buildClient(clientBuilder);
this.getConfig().configureClient(clientBuilder);
return clientBuilder.build();
}
/**
* @param clientBuilder A client builder
*/
public void buildClient(ClientBuilder clientBuilder) {
// for extension purposes
}
/**
* @param clientBuilder A client builder
*/
public void buildClient(ClientBuilder clientBuilder) {
// for extension purposes
}
/**
* @return A pre-configured JAX-RS target (client w/ base URL) with configured authorization.

View File

@@ -16,6 +16,11 @@ package com.inteligr8.rs;
import java.net.URI;
import javax.ws.rs.client.ClientBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
/**
* This interface defines the configurable parameters of the clients; primarily
* their default authentication and authorization.
@@ -114,6 +119,16 @@ public interface ClientConfiguration {
}
default Integer getConnectTimeoutInMillis() {
return null;
}
default Integer getResponseTimeoutInMillis() {
return null;
}
/**
* @return true to enable Jackson UNWRAP_ROOT_VALUE feature; false otherwise.
@@ -128,6 +143,18 @@ public interface ClientConfiguration {
default boolean isWrapRootValueEnabled() {
return false;
}
/**
* @param mapper A Jackson object mapper to configure.
*/
default void configureJacksonMapper(ObjectMapper mapper) {
}
/**
* @param provider A Jackson JAX-RS provider to configure.
*/
default void configureJacksonProvider(JacksonJaxbJsonProvider provider) {
}
@@ -169,5 +196,13 @@ public interface ClientConfiguration {
return null;
}
}
/**
* A Jackson provider, logging filter, and authentication filter are already registered.
*
* @param clientBuilder A JAX-RS client builder to configure.
*/
default void configureClient(ClientBuilder clientBuilder) {
}
}

View File

@@ -16,6 +16,8 @@ package com.inteligr8.rs;
import javax.ws.rs.client.ClientRequestContext;
import org.apache.commons.lang3.StringUtils;
/**
* This class is the base for implementations of client authorization similar
* to OAuth-based flows.
@@ -45,8 +47,8 @@ public class ClientEnforcementAuthorizationFilter implements AuthorizationFilter
* @param clientSecret A secret corresponding to the client ID.
*/
public ClientEnforcementAuthorizationFilter(String clientId, String clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.clientId = StringUtils.trimToNull(clientId);
this.clientSecret = StringUtils.trimToNull(clientSecret);
}
/**

View File

@@ -0,0 +1,79 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.rs;
import javax.annotation.PostConstruct;
import javax.ws.rs.client.ClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class that provides pre-configured JAX-RS Client &amp; WebTarget objects
* for Jersey.
*
* @author brian@inteligr8.com
*/
public class ClientImpl extends Client {
private final Logger logger = LoggerFactory.getLogger(ClientImpl.class);
private ClientConfiguration config;
/**
* This constructor is for Spring or POJO use.
* @param config The client configuration.
*/
public ClientImpl(ClientConfiguration config) {
this.config = config;
}
/**
* This method registers the Jersey library as the default provider for the
* JAX-RS specification.
*/
@PostConstruct
public void register() {
this.logger.info("API Base URL: {}", this.getConfig().getBaseUrl());
}
/**
* @param clientBuilder A client builder.
*/
@Override
public void buildClient(ClientBuilder clientBuilder) {
}
/**
* @return The client configuration.
*/
public ClientConfiguration getConfig() {
return this.config;
}
/**
* 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(AuthorizationFilter authFilter, Class<T> apiClass) {
throw new UnsupportedOperationException();
}
}

View File

@@ -58,7 +58,7 @@ public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter
logger.trace("request: {} {}: {}", requestContext.getMethod(), requestContext.getUri(),
((Form)requestContext.getEntity()).asMap());
} else {
this.loggerRequest.trace("request: {} {}: failed to output form", requestContext.getMethod(), requestContext.getUri());
logger.trace("request: {} {}: failed to output form", requestContext.getMethod(), requestContext.getUri());
}
} else {
this.logUnhandledRequest(requestContext, logger);

View File

@@ -18,6 +18,10 @@ import java.net.URI;
import javax.ws.rs.core.Form;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the OAuth Authorization Code flow as an authorization
* filter.
@@ -25,6 +29,8 @@ import javax.ws.rs.core.Form;
* @author brian@inteligr8.com
*/
public class OAuthAuthorizationCodeAuthorizationFilter extends OAuthAuthorizationFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String code;
private final URI redirectUri;
@@ -68,17 +74,22 @@ public class OAuthAuthorizationCodeAuthorizationFilter extends OAuthAuthorizatio
public OAuthAuthorizationCodeAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String code, URI redirectUri) {
super(tokenUrl, clientId, clientSecret);
this.code = code;
this.code = StringUtils.trimToNull(code);
this.redirectUri = redirectUri;
}
@Override
protected Form createForm() {
Form form = new Form().param("grant_type", "authorization_code")
.param("code", this.code);
this.logger.debug("Using OAuth grant_type 'authorization_code'");
Form form = new Form().param("grant_type", "authorization_code");
if (this.redirectUri != null)
form.param("redirect_uri", this.redirectUri.toString());
return form;
}
@Override
protected void extendFormSensitive(Form form) {
form.param("code", this.code);
}
}

View File

@@ -17,12 +17,19 @@ package com.inteligr8.rs;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
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 javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
@@ -33,6 +40,8 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
*/
public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String tokenUrl;
private final String clientId;
private final String clientSecret;
@@ -40,6 +49,7 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
private String accessToken;
private long expiration;
private String refreshToken;
private Long refreshTokenExpiration;
/**
* This constructor creates an OAuth-based authorization filter using the
@@ -79,9 +89,9 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
*/
public OAuthAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String scope) {
this.tokenUrl = tokenUrl;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.scope = scope;
this.clientId = StringUtils.trimToNull(clientId);
this.clientSecret = StringUtils.trimToNull(clientSecret);
this.scope = StringUtils.trimToNull(scope);
}
/**
@@ -91,8 +101,29 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
*/
@Override
public void filter(ClientRequestContext requestContext) {
if (this.accessToken == null || System.currentTimeMillis() > this.expiration)
this.requestToken();
if (this.accessToken == null) {
this.requestToken();
} else if (System.currentTimeMillis() >= this.expiration) {
this.logger.trace("Access token expired; retrieving new one with refresh token");
if (this.refreshTokenExpiration != null && System.currentTimeMillis() >= this.refreshTokenExpiration.longValue()) {
this.logger.debug("Refresh token expired; performing full authentication");
this.refreshToken = null;
this.requestToken();
} else {
try {
this.requestToken();
} catch (WebApplicationException wae) {
if (wae.getResponse().getStatusInfo().getFamily() == Family.CLIENT_ERROR) {
this.logger.debug("Received OAuth response {} using refresh token; performing full authentication", wae.getResponse().getStatus());
this.refreshToken = null;
this.requestToken();
} else {
throw wae;
}
}
}
}
requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + this.accessToken);
}
@@ -111,29 +142,53 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
}
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);
this.extendRefreshTokenForm(form);
this.logger.trace("Sending OAuth request: {}", form);
if (this.refreshToken != null) {
this.extendRefreshFormSensitive(form);
} else {
this.extendFormSensitive(form);
}
if (this.clientSecret != null)
form.param("client_secret", this.clientSecret);
Entity<Form> entity = Entity.form(form);
WebTarget target = ClientBuilder.newBuilder()
.register(new JacksonJaxbJsonProvider())
.build()
.target(this.tokenUrl);
Client client = ClientBuilder.newBuilder()
.register(new JacksonJaxbJsonProvider())
.build();
WebTarget target = client.target(this.tokenUrl);
long requestSendTime = System.currentTimeMillis();
@SuppressWarnings("unchecked")
Map<String, Object> response = target.request().post(entity, Map.class);
Response response = target.request().post(entity);
if (response.containsKey("error"))
throw new WebApplicationException((String)response.get("error"), 400);
this.logger.debug("Received OAuth response: {}", response.getStatus());
@SuppressWarnings("unchecked")
Map<String, Object> responseMap = response.readEntity(Map.class);
this.logger.trace("Received OAuth response: {}", responseMap);
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");
this.extendRefreshTokenResponse(response);
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String code = (String) responseMap.get("error");
if (code != null) {
String description = (String) responseMap.get("error_description");
throw new WebApplicationException(code + ": " + description, response.getStatus());
} else {
throw new WebApplicationException(response);
}
}
this.accessToken = (String)responseMap.get("access_token");
this.expiration = requestSendTime + ((Number)responseMap.get("expires_in")).longValue() * 1000L;
this.refreshToken = (String)responseMap.get("refresh_token");
if (responseMap.containsKey("refresh_token_expires_in"))
this.refreshTokenExpiration = requestSendTime + ((Number)responseMap.get("refresh_token_expires_in")).longValue() * 1000L;
}
protected Form createRefreshForm() {
@@ -143,10 +198,9 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
protected abstract Form createForm();
protected void extendRefreshTokenForm(Form form) {
}
protected void extendRefreshTokenResponse(Map<String, Object> response) {
protected void extendRefreshFormSensitive(Form form) {
}
protected abstract void extendFormSensitive(Form form);
}

View File

@@ -16,6 +16,9 @@ package com.inteligr8.rs;
import javax.ws.rs.core.Form;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the OAuth Client Credential flow as an authorization
* filter.
@@ -23,6 +26,8 @@ import javax.ws.rs.core.Form;
* @author brian@inteligr8.com
*/
public class OAuthClientCredentialAuthorizationFilter extends OAuthAuthorizationFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* @param tokenUrl The URL to the OAuth IdP token service.
@@ -35,7 +40,12 @@ public class OAuthClientCredentialAuthorizationFilter extends OAuthAuthorization
@Override
protected Form createForm() {
this.logger.debug("Using OAuth grant_type 'client_credentials'");
return new Form().param("grant_type", "client_credentials");
}
@Override
protected void extendFormSensitive(Form form) {
}
}

View File

@@ -16,6 +16,10 @@ package com.inteligr8.rs;
import javax.ws.rs.core.Form;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the OAuth Password Grant flow as an authorization
* filter.
@@ -23,6 +27,8 @@ import javax.ws.rs.core.Form;
* @author brian@inteligr8.com
*/
public class OAuthPasswordGrantAuthorizationFilter extends OAuthAuthorizationFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String username;
private final String password;
@@ -46,15 +52,20 @@ public class OAuthPasswordGrantAuthorizationFilter extends OAuthAuthorizationFil
*/
public OAuthPasswordGrantAuthorizationFilter(String tokenUrl, String clientId, String clientSecret, String username, String password) {
super(tokenUrl, clientId, clientSecret);
this.username = username;
this.password = password;
this.username = StringUtils.trimToNull(username);
this.password = StringUtils.trimToNull(password);
}
@Override
protected Form createForm() {
this.logger.debug("Using OAuth grant_type 'password': {}", this.username);
return new Form().param("grant_type", "password")
.param("username", this.username)
.param("password", this.password);
.param("username", this.username);
}
@Override
protected void extendFormSensitive(Form form) {
form.param("password", this.password);
}
}