简体   繁体   中英

java Apache Cxf HTTP authentication

I have WSDL . I need to make HTTP basic (preemptive) authentication. What to do?

I tried :

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

But it does not work: Caused by:

java.io.IOException: Server returned HTTP response code: 401 for URL ..

PS I use Apache CXF 2.6.2 and JBoss 5.0.1

What you specified for your authentication is not enough. You should do something like this:

private YourService proxy;

public YourServiceWrapper() {
    try {
        final String username = "username";
        final String password = "password";
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        username,
                        password.toCharArray());
            }
        });
        URL url = new URL("http://yourserviceurl/YourService?WSDL");
        QName qname = new QName("http://targetnamespace/of/your/wsdl", "YourServiceNameInWsdl");
        Service service = Service.create(url, qname);
        proxy = service.getPort(YourService.class);
        Map<String, Object> requestContext = ((BindingProvider) proxy).getRequestContext();
        requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());
        requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
        requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
    } catch (Exception e) {
        LOGGER.error("Error occurred in web service client initialization", e);
    }
}

Properties:

  1. YourService - your generated web service client interface.
  2. YourServiceWrapper() - wrapper class constructor which initializes your service.
  3. url - URL to your web service with ?WSDL extension.
  4. qname - first constructor argument: target namespace from your WSDL file. Second: your service name from WSDL .

Then you will be able to call your web service methods like this:

proxy.whatEverMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM