开发者

How to specify username/password in Java Metro?

开发者 https://www.devze.com 2023-03-25 21:13 出处:网络
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:

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.S开发者_Go百科erviceClient 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?


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号