001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 */ 012package org.nuxeo.ecm.automation.client.jaxrs.impl; 013 014import java.io.IOException; 015 016import org.apache.commons.logging.Log; 017import org.apache.commons.logging.LogFactory; 018import org.apache.http.HttpException; 019import org.apache.http.HttpHost; 020import org.apache.http.HttpRequest; 021import org.apache.http.HttpRequestInterceptor; 022import org.apache.http.auth.AuthScheme; 023import org.apache.http.auth.AuthScope; 024import org.apache.http.auth.AuthState; 025import org.apache.http.auth.Credentials; 026import org.apache.http.client.CredentialsProvider; 027import org.apache.http.client.protocol.ClientContext; 028import org.apache.http.protocol.ExecutionContext; 029import org.apache.http.protocol.HttpContext; 030 031public class HttpPreemptiveAuthInterceptor implements HttpRequestInterceptor { 032 033 protected static final Log log = LogFactory.getLog(HttpPreemptiveAuthInterceptor.class); 034 035 protected final AuthScheme authScheme; 036 037 HttpPreemptiveAuthInterceptor(AuthScheme authScheme) { 038 this.authScheme = authScheme; 039 } 040 041 @Override 042 public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { 043 AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 044 // If not auth scheme has been initialized yet 045 if (authState.getAuthScheme() != null) { 046 return; 047 } 048 049 // fetch credentials 050 CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); 051 HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); 052 AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); 053 054 // Obtain credentials matching the target host 055 Credentials creds = credsProvider.getCredentials(authScope); 056 057 if (creds == null) { 058 log.warn("no credentials provided for " + authScope); 059 return; 060 } 061 062 authState.setAuthScheme(authScheme); 063 authState.setCredentials(creds); 064 } 065 066}