001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.http.client.support;
018
019import java.io.IOException;
020import java.nio.charset.StandardCharsets;
021
022import org.springframework.http.HttpRequest;
023import org.springframework.http.client.ClientHttpRequestExecution;
024import org.springframework.http.client.ClientHttpRequestInterceptor;
025import org.springframework.http.client.ClientHttpResponse;
026import org.springframework.lang.Nullable;
027import org.springframework.util.Assert;
028import org.springframework.util.Base64Utils;
029
030/**
031 * {@link ClientHttpRequestInterceptor} to apply a BASIC authorization header.
032 *
033 * @author Phillip Webb
034 * @since 4.3.1
035 * @deprecated as of 5.1.1, in favor of {@link BasicAuthenticationInterceptor}
036 * which reuses {@link org.springframework.http.HttpHeaders#setBasicAuth},
037 * sharing its default charset ISO-8859-1 instead of UTF-8 as used here
038 */
039@Deprecated
040public class BasicAuthorizationInterceptor implements ClientHttpRequestInterceptor {
041
042        private final String username;
043
044        private final String password;
045
046
047        /**
048         * Create a new interceptor which adds a BASIC authorization header
049         * for the given username and password.
050         * @param username the username to use
051         * @param password the password to use
052         */
053        public BasicAuthorizationInterceptor(@Nullable String username, @Nullable String password) {
054                Assert.doesNotContain(username, ":", "Username must not contain a colon");
055                this.username = (username != null ? username : "");
056                this.password = (password != null ? password : "");
057        }
058
059
060        @Override
061        public ClientHttpResponse intercept(
062                        HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
063
064                String token = Base64Utils.encodeToString(
065                                (this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8));
066                request.getHeaders().add("Authorization", "Basic " + token);
067                return execution.execute(request, body);
068        }
069
070}