Skip to content

Instantly share code, notes, and snippets.

@maiostri
Created April 27, 2015 19:35
Show Gist options
  • Save maiostri/46e3ba363000518b3e41 to your computer and use it in GitHub Desktop.
Save maiostri/46e3ba363000518b3e41 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
/**
* HTTP Request interceptor responsible for adding the Basic authentication
* header to requests addressed to Chargify.
*
*/
public class BasicAuthInterceptor implements ClientHttpRequestInterceptor {
private final String username;
private final String password;
public BasicAuthInterceptor(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
final String auth = username + ":" + password;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
final String authHeader = "Basic " + new String(encodedAuth);
request.getHeaders().add("Authorization", authHeader);
return execution.execute(request, body);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment