Search code examples
javajava-metro-framework

How to specify username/password in Java Metro?


I'm trying to create a Web Service Client with Metro that uses WS-Security.

I have used Axis2, and to specify the username/password in an Axis2 client, I do:

org.apache.axis2.client.ServiceClient sc = stub._getServiceClient();
org.apache.axis2.client.Options options = sc.getOptions();
options.setUserName("USERNAME");
options.setPassword("PASSWORD");

How do I provide a username/password in a Metro client?


Solution

  • If you want to auth using basic http headers:

    @WebEndpoint(name = "WSHttpBinding_ICustomerService")
    public ICustomerService getWSHttpBindingICustomerService() {
        WebServiceFeature wsAddressing = new AddressingFeature(true);
    
        ICustomerService service =
            super.getPort(new QName("http://xmlns.example.com/services/Customer",
                    "WSHttpBinding_ICustomerService"), ICustomerService.class, 
                    wsAddressing);
    
        Map<String, Object> context = ((BindingProvider)service).getRequestContext();
    
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList("yourusername"));
        headers.put("Password", Collections.singletonList("yourpassword"));
    
        return service;
    }
    

    If the service uses NTLM (Windows authentication) (explanation here):

    @WebEndpoint(name = "WSHttpBinding_ICustomerService")
    public ICustomerService getWSHttpBindingICustomerService() {
        WebServiceFeature wsAddressing = new AddressingFeature(true);
    
        ICustomerService service =
            super.getPort(new QName("http://xmlns.example.com/services/Customer",
                    "WSHttpBinding_ICustomerService"), ICustomerService.class, 
                    wsAddressing);
    
        NtlmAuthenticator auth = new NtlmAuthenticator(username, password);  
        Authenticator.setDefault(auth);   
    
        return service;
    }
    

    Haven't used this myself, but seen other use it:

    @WebEndpoint(name = "WSHttpBinding_ICustomerService")
    public ICustomerService getWSHttpBindingICustomerService() {
        WebServiceFeature wsAddressing = new AddressingFeature(true);
    
        ICustomerService service =
            super.getPort(new QName("http://xmlns.example.com/services/Customer",
                    "WSHttpBinding_ICustomerService"), ICustomerService.class, 
                    wsAddressing);
    
        Map<String, Object> context = ((BindingProvider)service).getRequestContext();
    
        context.put(BindingProvider.USERNAME_PROPERTY, "yourusername");
        context.put(BindingProvider.PASSWORD_PROPERTY, "yourpassword");
    
        return service;
    }