#if JAVA
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.Proxy;
import java.util.List;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
import org.apache.http.impl.auth.NTLMScheme;
import anywheresoftware.b4h.okhttp.OkHttpClientWrapper;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public static void SetNTLM(String username, String password, String domain, String workstation, OkHttpClientWrapper OkHttpClient) throws Exception {
OkHttpClient.client.setAuthenticator(new NTLMAuthenticator(username, password, domain, workstation));
}
public static class NTLMAuthenticator implements Authenticator {
final NTLMEngine engine;
private final String domain;
private final String username;
private final String password;
private final String ntlmMsg1;
private final String workstation;
public NTLMAuthenticator(String username, String password, String domain, String workstation) throws Exception {
this.domain = domain;
this.username = username;
this.workstation = workstation;
this.password = password;
NTLMScheme scheme = new NTLMScheme();
Field f = scheme.getClass().getDeclaredField("engine");
f.setAccessible(true);
engine = (NTLMEngine)f.get(scheme);
String localNtlmMsg1 = null;
localNtlmMsg1 = engine.generateType1Msg(domain, workstation);
ntlmMsg1 = localNtlmMsg1;
}
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
final List<String> WWWAuthenticate = response.headers().values("WWW-Authenticate");
if (WWWAuthenticate.contains("NTLM")) {
return response.request().newBuilder().header("Authorization", "NTLM " + ntlmMsg1).build();
}
String ntlmMsg3 = null;
try {
ntlmMsg3 = engine.generateType3Msg(username, password, domain, workstation, WWWAuthenticate.get(0).substring(5));
} catch (NTLMEngineException e) {
throw new RuntimeException(e);
}
return response.request().newBuilder().header("Authorization", "NTLM " + ntlmMsg3).build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
}
#end if