001/* 002 * Copyright 2002-2016 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.Charset; 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.util.Assert; 027import org.springframework.util.Base64Utils; 028 029/** 030 * {@link ClientHttpRequestInterceptor} to apply a BASIC authorization header. 031 * 032 * @author Phillip Webb 033 * @since 4.3.1 034 */ 035public class BasicAuthorizationInterceptor implements ClientHttpRequestInterceptor { 036 037 private static final Charset UTF_8 = Charset.forName("UTF-8"); 038 039 private final String username; 040 041 private final String password; 042 043 044 /** 045 * Create a new interceptor which adds a BASIC authorization header 046 * for the given username and password. 047 * @param username the username to use 048 * @param password the password to use 049 */ 050 public BasicAuthorizationInterceptor(String username, String password) { 051 Assert.hasLength(username, "Username must not be empty"); 052 this.username = username; 053 this.password = (password != null ? password : ""); 054 } 055 056 057 @Override 058 public ClientHttpResponse intercept(HttpRequest request, byte[] body, 059 ClientHttpRequestExecution execution) throws IOException { 060 061 String token = Base64Utils.encodeToString((this.username + ":" + this.password).getBytes(UTF_8)); 062 request.getHeaders().add("Authorization", "Basic " + token); 063 return execution.execute(request, body); 064 } 065 066}