Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I consume a web service protected with HTTP basic authentication using the CXF framework?

I tried to get it to work using the CXF User Guide, but I've had no luck.

I'm trying to call the web service using java code.

like image 924
ScArcher2 Avatar asked Apr 01 '09 14:04

ScArcher2


3 Answers

This is covered by the JAX-WS Specification. Basically, set the username/password as properties on the request context:

((BindingProvider)proxy).getRequestContext().put(
    BindingProvider.USERNAME_PROPERTY, "joe");
((BindingProvider)proxy).getRequestContext().put(
    BindingProvider.PASSWORD_PROPERTY, "pswd");

The runtime puts them into the HTTP header.

like image 173
Daniel Kulp Avatar answered Oct 15 '22 10:10

Daniel Kulp


You can provide your own Authenticator. That way it will work if the WDSL itself is protected by basic HTTP authentication.

@WebServiceRef(wsdlLocation = "https://laka/sito?wsdl")
static XxxService service;

public static void main(String[] args) {

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("user", "password".toCharArray());
        }
    });

    service = new XxxService();
    Xxx port = service.getXxxPort();

    // invoke webservice and print response
    XxxResponse resp = port.foo();
    System.out.println(resp.toString());

}
like image 8
mikeltxo Avatar answered Oct 15 '22 12:10

mikeltxo


There is a much better way:

when generating Java from WSDL, add option "-exsh true" :

wsdl2java -exsh true -p edu.sharif.ce http://wsdl.ir/WebServices/WebService.asmx?WSDL

and add UserCredential when using:

UserCredentials user = new UserCredentials();
user.setUserid("user");
user.setPassword("pass");

ResearchWebService_Service service = new ResearchWebService_Service();
ResearchWebService port = service.getResearchWebService();
port.addNewProject(newProject, user);
like image 6
Mohammad Dashti Avatar answered Oct 15 '22 12:10

Mohammad Dashti