2009-04-01 7 views

risposta

24

Questo è coperto dalla specifica JAX-WS. Fondamentalmente, impostare il nome utente/password come proprietà nel contesto della richiesta:

((BindingProvider)proxy).getRequestContext().put(
    BindingProvider.USERNAME_PROPERTY, "joe"); 
((BindingProvider)proxy).getRequestContext().put(
    BindingProvider.PASSWORD_PROPERTY, "pswd"); 

Il runtime li inserisce nell'intestazione HTTP.

+5

Potrebbe essere utile menzionare che è sufficiente eseguire il cast della porta CXF: BindingProvider portBP = (BindingProvider) port; portBP.getRequestContext(). Put (BindingProvider.USERNAME_PROPERTY, "username"); portBP.getRequestContext(). Put (BindingProvider.PASSWORD_PROPERTY, "password"); – Francois

6

C'è un modo molto migliore:

durante la generazione di Java da WSDL, aggiungere l'opzione "-exsh vero":

WSDL2Java -exsh vero -p edu.sharif.ce http://wsdl.ir/WebServices/WebService.asmx?WSDL

e aggiungi UserCredential quando si utilizza:

UserCredentials user = new UserCredentials(); 
user.setUserid("user"); 
user.setPassword("pass"); 

ResearchWebService_Service service = new ResearchWebService_Service(); 
ResearchWebService port = service.getResearchWebService(); 
port.addNewProject(newProject, user); 
+0

Sei sicuro che abiliterà l'autenticazione di base nelle intestazioni delle richieste HTTP? Questo probabilmente imposterà le credenziali all'interno del messaggio SOAP invece di impostare un'intestazione HTTP di autorizzazione ... (poiché i documenti dicono che opera su "impliciti soap headers") – Geert

7

È possibile fornire il proprio Authenticator. In questo modo funzionerà se il WDSL stesso è protetto dall'autenticazione HTTP di base.

@WebServiceRef(wsdlLocation = "https://laka/sito?wsdl") 
static XxxService service; 

public static void main(String[] args) { 

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

    service = new XxxService(); 
    Xxx port = service.getXxxPort(); 

    // invoke webservice and print response 
    XxxResponse resp = port.foo(); 
    System.out.println(resp.toString()); 

} 
+0

Nota che il metodo 'Authenticator.setDefault (Authenticator)' è statico e quindi si applicherà a tutti i tuoi thread. Tuttavia, è abbastanza facile aggirare questo usando una variabile 'ThreadLocal' per salvare informazioni di autenticazione differenti per thread. – Marco

+1

Vedo 'Authenticator.setDefault' è statico ma è anche un metodo sincronizzato. Ha davvero bisogno di usare ThreadLocal? –

Problemi correlati