Commit ab6b0d8d authored by Brian Long's avatar Brian Long
Browse files

refacter OAuth filter error handling

parent c25988fc
Loading
Loading
Loading
Loading
+83 −0
Original line number Diff line number Diff line
/*
 * 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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * A class that provides pre-configured JAX-RS Client &amp; WebTarget objects
 * for Jersey.
 * 
 * @author brian@inteligr8.com
 */
@Component("client.jaxrs")
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.
	 */
	@Autowired
	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();
	}

}
+1 −1
Original line number Diff line number Diff line
@@ -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);
+23 −19
Original line number Diff line number Diff line
@@ -17,12 +17,15 @@ 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 com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;

@@ -115,25 +118,32 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
			form.param("client_secret", this.clientSecret);
		if (this.scope != null)
			form.param("scope", this.scope);
		this.extendRefreshTokenForm(form);
		
		Entity<Form> entity = Entity.form(form);
		
		WebTarget target = ClientBuilder.newBuilder()
		Client client = ClientBuilder.newBuilder()
                .register(new JacksonJaxbJsonProvider())
				.build()
				.target(this.tokenUrl);
                .build();
		WebTarget target = client.target(this.tokenUrl);

		Response response = target.request().post(entity);

        @SuppressWarnings("unchecked")
		Map<String, Object> response = target.request().post(entity, Map.class);
        Map<String, Object> responseMap = response.readEntity(Map.class);
		
		if (response.containsKey("error"))
			throw new WebApplicationException((String)response.get("error"), 400);
		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)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);
		this.accessToken = (String)responseMap.get("access_token");
		this.expiration = System.currentTimeMillis() + ((Number)responseMap.get("expires_in")).longValue() * 1000L;
		this.refreshToken = (String)responseMap.get("refresh_token");
	}
	
	protected Form createRefreshForm() {
@@ -143,10 +153,4 @@ public abstract class OAuthAuthorizationFilter implements AuthorizationFilter {
	
	protected abstract Form createForm();

	protected void extendRefreshTokenForm(Form form) {
	}
	
	protected void extendRefreshTokenResponse(Map<String, Object> response) {
	}

}