001package ca.uhn.fhir.rest.client.interceptor; 002 003/* 004 * #%L 005 * HAPI FHIR - Client Framework 006 * %% 007 * Copyright (C) 2014 - 2019 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; 032import org.apache.commons.lang3.Validate; 033 034/** 035 * HTTP interceptor to be used for adding HTTP basic auth username/password tokens 036 * to requests 037 * <p> 038 * See the <a href="http://jamesagnew.github.io/hapi-fhir/doc_rest_client_interceptor.html#Security_HTTP_Basic_Authorization">HAPI Documentation</a> 039 * for information on how to use this class. 040 * </p> 041 */ 042public class BasicAuthInterceptor implements IClientInterceptor { 043 044 private String myUsername; 045 private String myPassword; 046 private String myHeaderValue; 047 048 /** 049 * @param theUsername The username 050 * @param thePassword The password 051 */ 052 public BasicAuthInterceptor(String theUsername, String thePassword) { 053 this(StringUtils.defaultString(theUsername) + ":" + StringUtils.defaultString(thePassword)); 054 } 055 056 /** 057 * @param theCredentialString A credential string in the format <code>username:password</code> 058 */ 059 public BasicAuthInterceptor(String theCredentialString) { 060 Validate.notBlank(theCredentialString, "theCredentialString must not be null or blank"); 061 Validate.isTrue(theCredentialString.contains(":"), "theCredentialString must be in the format 'username:password'"); 062 String encoded = Base64.encodeBase64String(theCredentialString.getBytes(Constants.CHARSET_US_ASCII)); 063 myHeaderValue = "Basic " + encoded; 064 } 065 066 @Override 067 public void interceptRequest(IHttpRequest theRequest) { 068 theRequest.addHeader(Constants.HEADER_AUTHORIZATION, myHeaderValue); 069 } 070 071 @Override 072 public void interceptResponse(IHttpResponse theResponse) throws IOException { 073 // nothing 074 } 075 076}