001/*
002 * (C) Copyright 2006-20012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Antoine Taillefer
016 */
017package org.nuxeo.ecm.automation.client.jaxrs.spi.auth;
018
019import org.nuxeo.ecm.automation.client.jaxrs.spi.Connector;
020import org.nuxeo.ecm.automation.client.jaxrs.spi.Request;
021import org.nuxeo.ecm.automation.client.jaxrs.spi.RequestInterceptor;
022
023import com.sun.jersey.api.client.ClientHandlerException;
024import com.sun.jersey.api.client.ClientRequest;
025import com.sun.jersey.api.client.ClientResponse;
026
027/**
028 * Injects the token authentication header in the request.
029 *
030 * @author Antoine Taillefer (ataillefer@nuxeo.com)
031 * @since 5.7
032 */
033public class TokenAuthInterceptor extends RequestInterceptor {
034
035    protected static final String TOKEN_HEADER = "X-Authentication-Token";
036
037    protected String token;
038
039    public TokenAuthInterceptor(String token) {
040        this.token = token;
041    }
042
043    @Override
044    public void processRequest(Request request, Connector connector) {
045        request.put(TOKEN_HEADER, token);
046    }
047
048    @Override
049    public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
050        if (!cr.getHeaders().containsKey(TOKEN_HEADER)) {
051            cr.getHeaders().add(TOKEN_HEADER, token);
052        }
053        return getNext().handle(cr);
054    }
055}