Sunday, June 29, 2014

Spring Web service with NTLM Authentication

Spring Web service with NTLM Authentication

NTLM is a proprietary authentication scheme developed by Microsoft and optimized for Windows operating system.

This post will explain how to invoke the NTLM authentication enabled web services from spring integration.

Spring Web Service uses the Apache HTTPClient to communicate to the NTLM authentication enabled services.

We named our spring bean as WebServiceNTLMAuhCommunicationClientImpl, it will extend the class org.springframework.ws.client.core.support.WebServiceGatewaySupport

We have overridden the method initGateway to set the org.apache.commons.httpclient.NTCredentials object to CommonsHttpMessageSender.

The userName, password and the domain name should be provided to createthe NTCredential object.

The afterPropertiesSet method on CommonsHttpMessageSender class should be invoked after setting the credential - afterPropertiesSet method will set the credentials to HttPClient.

WebServiceNTLMAuhCommunicationClientImpl.java

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.NTCredentials;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.transport.http.CommonsHttpMessageSender;

public class WebServiceNTLMAuhCommunicationClientImpl extends WebServiceGatewaySupport {
 private String basicAuthUsername;
 private String basicAuthPassword;
 private String domain;
 private String hostname;


 public String getHostname() {
  return hostname;
 }

  public void setHostname(String hostname) {
  this.hostname = hostname;
 }

  public Object send(String url, Object request)
 {
  return this.getWebServiceTemplate().marshalSendAndReceive(
    url, request, null);
 }

 public void setBasicAuthPassword(String basicAuthPassword)
    {
     this.basicAuthPassword = basicAuthPassword;
    }

  public void setBasicAuthUsername(String basicAuthUsername)
    {
     this.basicAuthUsername = basicAuthUsername;
    }

 public String getDomain() {
  return domain;
 }

  public void setDomain(String domain) {
  this.domain = domain;
 }

  @Override
    protected void initGateway() throws Exception
    {
  if(this.basicAuthUsername != null || this.basicAuthPassword != null)
  {
    ((CommonsHttpMessageSender)this.getMessageSenders()[0]).setCredentials(getCredentials());
    ((CommonsHttpMessageSender)this.getMessageSenders()[0]).afterPropertiesSet();
  }
  super.initGateway();
    }

 private Credentials getCredentials() {
   return new NTCredentials(this.basicAuthUsername, this.basicAuthPassword, getHostname(), getDomain());
 }

}



No comments:

Post a Comment