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