Java Apache Cxf HTTP Authentication

I have a WSDL . I need to do HTTP basic (proactive) authentication. What to do?

I tried:

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

But this does not work: caused by:

java.io.IOException: The server responded with an HTTP: 401 response code for the URL.

PS I am using Apache CXF 2.6.2 and JBoss 5.0.1

+4
source share
1 answer

What you provided for your authentication is not enough. You should do something like this:

 private YourService proxy; public YourServiceWrapper() { try { final String username = "username"; final String password = "password"; Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( username, password.toCharArray()); } }); URL url = new URL("http://yourserviceurl/YourService?WSDL"); QName qname = new QName("http://targetnamespace/of/your/wsdl", "YourServiceNameInWsdl"); Service service = Service.create(url, qname); proxy = service.getPort(YourService.class); Map<String, Object> requestContext = ((BindingProvider) proxy).getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString()); requestContext.put(BindingProvider.USERNAME_PROPERTY, username); requestContext.put(BindingProvider.PASSWORD_PROPERTY, password); Map<String, List<String>> headers = new HashMap<String, List<String>>(); requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } catch (Exception e) { LOGGER.error("Error occurred in web service client initialization", e); } } 

Properties:

  • YourService is your generated web service client interface.
  • YourServiceWrapper () is the constructor of the wrapper class that initializes your service.
  • url - URL of your web service with the extension ?WSDL .
  • qname is the first argument to the constructor: the target namespace from your WSDL file. Second: your service name is from WSDL .

You can then call your web service methods as follows:

 proxy.whatEverMethod(); 
+15
source

Source: https://habr.com/ru/post/1439753/


All Articles