如何在Java Metro中指定用户名/密码?

时间:2011-08-03 20:17:26

标签: java java-metro-framework

我正在尝试使用使用WS-Security的Metro创建Web服务客户端。

我使用过Axis2,并在Axis2客户端中指定用户名/密码,我这样做:

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

如何在Metro客户端中提供用户名/密码?

1 个答案:

答案 0 :(得分:4)

如果您想使用基本的http标头进行身份验证:

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

如果服务使用NTLM(Windows身份验证)(解释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;
}

我自己没有使用它,但看到其他用途:

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