001package ca.uhn.fhir.rest.client.interceptor; 002 003/* 004 * #%L 005 * HAPI FHIR - Client Framework 006 * %% 007 * Copyright (C) 2014 - 2018 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; 028 029import ca.uhn.fhir.rest.api.Constants; 030import ca.uhn.fhir.rest.client.api.*; 031import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 032 033/** 034 * HTTP interceptor to be used for adding HTTP basic auth username/password tokens 035 * to requests 036 * <p> 037 * See the <a href="http://jamesagnew.github.io/hapi-fhir/doc_rest_client_interceptor.html#Security_HTTP_Basic_Authorization">HAPI Documentation</a> 038 * for information on how to use this class. 039 * </p> 040 */ 041public class BasicAuthInterceptor implements IClientInterceptor { 042 043 private String myUsername; 044 private String myPassword; 045 046 public BasicAuthInterceptor(String theUsername, String thePassword) { 047 super(); 048 myUsername = theUsername; 049 myPassword = thePassword; 050 } 051 052 @Override 053 public void interceptRequest(IHttpRequest theRequest) { 054 String authorizationUnescaped = StringUtils.defaultString(myUsername) + ":" + StringUtils.defaultString(myPassword); 055 String encoded; 056 try { 057 encoded = Base64.encodeBase64String(authorizationUnescaped.getBytes("ISO-8859-1")); 058 } catch (UnsupportedEncodingException e) { 059 throw new InternalErrorException("Could not find US-ASCII encoding. This shouldn't happen!"); 060 } 061 theRequest.addHeader(Constants.HEADER_AUTHORIZATION, ("Basic " + encoded)); 062 } 063 064 @Override 065 public void interceptResponse(IHttpResponse theResponse) throws IOException { 066 // nothing 067 } 068 069 070 071}