2011-08-03 38 views
0

我正在嘗試使用WS-Security創建一個使用Metro的Web服務客戶端。如何在Java Metro中指定用戶名/密碼?

我已經使用Axis2和在一個Axis2客戶端指定的用戶名/密碼,我做的:

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

如何在地鐵客戶端提供用戶名/密碼?

回答

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

謝謝!您的第一個示例中的變量標題已設置但未使用。有一些缺失。 –

相關問題