Sunday, August 6, 2017

How to implement NTLM security in WSO2 ESB

Unfortunately, WSO2 does not provide any plugins or mediator directly to implement NTLM security. However, this can be done by using the custom mediator. You can write a java class with this security handler and call it from WSO2 container.

In order to write a Class mediator, you can follow this blog and put the custom jar into the WSO2 lib folder.  



package poc.ntlm;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class NLTMSecurity {

 public static void main(String[] args) throws HttpException, IOException {
  System.out.println("started");
  String result = invokeService();
  System.out.println("output  : " + result);

 }

 public static String invokeService()
   throws HttpException, IOException {
  String responseString = null;
  try {
   HttpClient client = new HttpClient();

   String URL = "http://XXX.XXX.XXX/XX/XXX/2011/OrganizationData.svc/ListSet?$select=ListId,ListName,StateCode";
   GetMethod getMethod = new GetMethod(URL);
   NTCredentials credentials = new NTCredentials("USER_NAME", "PASSWORD", "HOST_NAME", "DOMAIN");
   client.getState().setCredentials(new AuthScope(null, -1, null),
     credentials);
   int status = client.executeMethod(getMethod);

   System.out.println("Status : " + status);

   responseString = getMethod.getResponseBodyAsString();

   System.out.println("responseString : " + responseString);

  } catch (Exception e) {
   System.out.println(e);
  }

  return responseString;

 }

}




You can set this response and the HTTP code in the WSO2 ESB container.



import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;


public class NTLMSecurityMediator extends AbstractMediator { 

 public boolean mediate(MessageContext context) { 

 context.setProperty("Response", responseString );
      
context.setProperty("HTTP_STATUS", status );      return true;
      
    
  
 }
}