Skip to content

Instantly share code, notes, and snippets.

@yamanyar
Created September 12, 2013 14:20
Show Gist options
  • Save yamanyar/6538217 to your computer and use it in GitHub Desktop.
Save yamanyar/6538217 to your computer and use it in GitHub Desktop.
A simple HttpComponentsMessageSender to use in spring integration with out bound ws gateway to authenticate with NTLM
package com.secretcompany.esb.util.exchange;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.xml.security.utils.Base64;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.ws.transport.WebServiceConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.util.Enumeration;
public class BasicToNTLMHttpComponentsMessageSender extends org.springframework.ws.transport.http.HttpComponentsMessageSender {
public BasicToNTLMHttpComponentsMessageSender() {
super();
}
public BasicToNTLMHttpComponentsMessageSender(HttpClient httpClient) {
super(httpClient);
}
@Override
public WebServiceConnection createConnection(URI uri) throws IOException {
init();
return super.createConnection(uri); //To change body of overridden methods use File | Settings | File Templates.
}
private void init() {
DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient();
String[] basicAuthenticationCredentials = getBasicAuthenticationCredentials();
if (basicAuthenticationCredentials != null) {
httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1), //to force use mail.yapikredi.com.tr
new NTCredentials(basicAuthenticationCredentials[0], basicAuthenticationCredentials[1], "secretprod1", "thedomain"));
}
}
private String[] getBasicAuthenticationCredentials() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String s = headerNames.nextElement();
try {
if ("authorization".equals(s.toLowerCase())) {
String encoded = request.getHeader(s).trim().split(" ")[1];
return new String(Base64.decode(encoded), "utf-8").split(":");
}
} catch (Exception e) {
logger.error("Can not decode basic authenticate", e);
return null;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment