001/*
002 * #%L
003 * HAPI FHIR - Client Framework
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.rest.client.impl;
021
022import org.apache.http.HttpException;
023import org.apache.http.HttpRequest;
024import org.apache.http.HttpRequestInterceptor;
025import org.apache.http.auth.AuthState;
026import org.apache.http.auth.Credentials;
027import org.apache.http.auth.UsernamePasswordCredentials;
028import org.apache.http.client.protocol.HttpClientContext;
029import org.apache.http.impl.auth.BasicScheme;
030import org.apache.http.protocol.HttpContext;
031
032import java.io.IOException;
033
034/**
035 * Apache HTTPClient interceptor which adds basic auth
036 *
037 * @see ca.uhn.fhir.rest.client.interceptor.BasicAuthInterceptor A HAPI FHIR interceptor that is generally easier to use
038 */
039public class HttpBasicAuthInterceptor implements HttpRequestInterceptor {
040
041        private String myUsername;
042        private String myPassword;
043
044        public HttpBasicAuthInterceptor(String theUsername, String thePassword) {
045                super();
046                myUsername = theUsername;
047                myPassword = thePassword;
048        }
049
050        @Override
051        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
052                AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
053
054                if (authState.getAuthScheme() == null) {
055                        Credentials creds = new UsernamePasswordCredentials(myUsername, myPassword);
056                        authState.update(new BasicScheme(), creds);
057                }
058        }
059}