Java Network LAN Manager Authentication

Java Network LAN Manager Authentication (NTLM Authentication)

Java URL connections works fine from home/public networks. But these won't work from corporate networks due to proxy issues.

To overcome this we set proxy properties in the system properties as below.

Proxy system properties

System.setProperty("http.proxySet", "true");
System.setProperty("", "true");
System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port");
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");

This works for some, and in some networks this will not work
When you end up with the IOException : Bad response: (407Proxy Authentication required) it means a proxy authentication is required.

Java provides a solution to this using
Write your own Authenticator to serve username and password of you closed network.

Custom Proxy Aunthenticator

public class ProxyAuthenticator extends{
 private String user, password;

    public ProxyAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;

    protected getPasswordAuthentication() {
     System.out.println("Authentication required.");     
        return new PasswordAuthentication(user, password.toCharArray());


Before you open a URL connection add the below code

//set Authenticator
Authenticator.setDefault(new ProxyAuthenticator("user", "password"));

//Then set the usual stuff
System.setProperty("http.proxyHost", "");
System.setProperty("http.proxyPort", "port");

//Here goes URL processing
URLConnection conn = url.openConnection();

This will pass through proxy authentication and connection will work fine.
In case you have an error in username/password - you can see the sop "Authentication required" will keep printed and you will end up with 403 Forbidden (bad password).
Make sure to include your domain in the username (domain\user). On a string it should be "domain\\user"


Post a Comment

Popular posts from this blog

SVN File Creation Date

Java NIO2 - Watching a directory for changes. FileWatcherService.

Ubuntu / kubuntu - Laptop key board cursor jumping issue