001package ca.uhn.fhir.rest.client.interceptor; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2016 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import java.io.IOException; 024import java.io.UnsupportedEncodingException; 025 026import org.apache.commons.codec.binary.Base64; 027import org.apache.commons.lang3.StringUtils; 028import org.apache.http.HttpResponse; 029import org.apache.http.client.methods.HttpRequestBase; 030 031import ca.uhn.fhir.rest.client.IClientInterceptor; 032import ca.uhn.fhir.rest.server.Constants; 033import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 034 035/** 036 * HTTP interceptor to be used for adding HTTP basic auth username/password tokens 037 * to requests 038 * <p> 039 * See the <a href="http://jamesagnew.github.io/hapi-fhir/doc_rest_client_interceptor.html#Security_HTTP_Basic_Authorization">HAPI Documentation</a> 040 * for information on how to use this class. 041 * </p> 042 */ 043public class BasicAuthInterceptor implements IClientInterceptor { 044 045 private String myUsername; 046 private String myPassword; 047 048 public BasicAuthInterceptor(String theUsername, String thePassword) { 049 super(); 050 myUsername = theUsername; 051 myPassword = thePassword; 052 } 053 054 @Override 055 public void interceptRequest(HttpRequestBase theRequest) { 056 String authorizationUnescaped = StringUtils.defaultString(myUsername) + ":" + StringUtils.defaultString(myPassword); 057 String encoded; 058 try { 059 encoded = Base64.encodeBase64String(authorizationUnescaped.getBytes("ISO-8859-1")); 060 } catch (UnsupportedEncodingException e) { 061 throw new InternalErrorException("Could not find US-ASCII encoding. This shouldn't happen!"); 062 } 063 theRequest.addHeader(Constants.HEADER_AUTHORIZATION, ("Basic " + encoded)); 064 } 065 066 @Override 067 public void interceptResponse(HttpResponse theResponse) throws IOException { 068 // nothing 069 } 070 071 072 073}