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.spi.auth; 020 021import static java.nio.charset.StandardCharsets.UTF_8; 022 023import javax.ws.rs.core.HttpHeaders; 024 025import org.apache.commons.codec.binary.Base64; 026import org.nuxeo.ecm.automation.client.jaxrs.spi.Connector; 027import org.nuxeo.ecm.automation.client.jaxrs.spi.Request; 028import org.nuxeo.ecm.automation.client.jaxrs.spi.RequestInterceptor; 029 030import com.sun.jersey.api.client.ClientHandlerException; 031import com.sun.jersey.api.client.ClientRequest; 032import com.sun.jersey.api.client.ClientResponse; 033 034/** 035 * Inject the basic authentication header in the request. 036 * 037 * @author matic 038 */ 039public class BasicAuthInterceptor extends RequestInterceptor { 040 041 protected String token; 042 043 public BasicAuthInterceptor(String username, String password) { 044 setAuth(username, password); 045 } 046 047 public void setAuth(String username, String password) { 048 String info = username + ":" + password; 049 token = "Basic " + Base64.encodeBase64String(info.getBytes(UTF_8)); 050 } 051 052 @Override 053 public void processRequest(Request request, Connector connector) { 054 request.put(HttpHeaders.AUTHORIZATION, token); 055 } 056 057 @Override 058 public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { 059 if (!cr.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { 060 cr.getHeaders().add(HttpHeaders.AUTHORIZATION, token); 061 } 062 return getNext().handle(cr); 063 } 064}