001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 */ 019package org.nuxeo.ecm.automation.client.jaxrs.impl; 020 021import java.io.IOException; 022 023import org.apache.commons.logging.Log; 024import org.apache.commons.logging.LogFactory; 025import org.apache.http.HttpException; 026import org.apache.http.HttpHost; 027import org.apache.http.HttpRequest; 028import org.apache.http.HttpRequestInterceptor; 029import org.apache.http.auth.AuthScheme; 030import org.apache.http.auth.AuthScope; 031import org.apache.http.auth.AuthState; 032import org.apache.http.auth.Credentials; 033import org.apache.http.client.CredentialsProvider; 034import org.apache.http.client.protocol.ClientContext; 035import org.apache.http.protocol.ExecutionContext; 036import org.apache.http.protocol.HttpContext; 037 038public class HttpPreemptiveAuthInterceptor implements HttpRequestInterceptor { 039 040 protected static final Log log = LogFactory.getLog(HttpPreemptiveAuthInterceptor.class); 041 042 protected final AuthScheme authScheme; 043 044 HttpPreemptiveAuthInterceptor(AuthScheme authScheme) { 045 this.authScheme = authScheme; 046 } 047 048 @Override 049 public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { 050 AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 051 // If not auth scheme has been initialized yet 052 if (authState.getAuthScheme() != null) { 053 return; 054 } 055 056 // fetch credentials 057 CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); 058 HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); 059 AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); 060 061 // Obtain credentials matching the target host 062 Credentials creds = credsProvider.getCredentials(authScope); 063 064 if (creds == null) { 065 log.warn("no credentials provided for " + authScope); 066 return; 067 } 068 069 authState.setAuthScheme(authScheme); 070 authState.setCredentials(creds); 071 } 072 073}