Share this page 

Do basic authentication when calling a webservice Tag(s): Networking


You have a web service, generated with JAX-WS or something else. You have the required client class but you need to provide a username/password. This can done easily with the help of the java.net.Authenticator. In this snippet, we are using an anonymous Authenticator to pass the credentials.

java.net.Authenticator myAuth = new java.net.Authenticator() {
  @Override
  protected java.net.PasswordAuthentication getPasswordAuthentication() {
  return new java.net.PasswordAuthentication("ws.user", "ws.pwd".toCharArray());
  }
};
java.net.Authenticator.setDefault(myAuth);

MyWebService myws = new MyWebService(new URL(url));
MyWebServicesHost mywsh  = myws.getMyServicesHostPort();
logger.info(" result :" + mywsh.myFunction("42"));
or use a regular class instead of an anonymous one.
import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
    private String user;
    private String password;

    public MyAuthenticator(String user,String password) {
      this.user = user;
      this.password = password;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        PasswordAuthentication auth = new PasswordAuthentication(user,password.toCharArray());
        return auth;
    }
}
WS authentication from Weblogic
WLS uses its own HTTP protocol implementation, so the above technique won't work, a 401 return code is always returned.

So if from Weblogic, you need to call a Web service and identify yourself using HTTP BASIC then you need to make sure to use the Sun's HTTP implementation, not the default and "push" the credentials.

import javax.xml.ws.BindingProvider;
...

URL url;
if (wsUrl.startsWith("https")) {
    url = new URL(null, svcUrl, new sun.net.www.protocol.https.Handler());
}

else {
    url = new URL(null, svcUrl, new sun.net.www.protocol.http.Handler());
}


MyWebService myws = new MyWebService(url);
MyWebServicesHost mywsh  = myws.getMyServicesHostPort();

((BindingProvider)engine).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "username");
((BindingProvider)engine).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "password");

logger.info(" result :" + mywsh.myFunction("42"));