How do I access this secure Soap webservice implemented by an EJB:
@Stateless
@DeclareRoles({"Boss"})
@WebService(name="SoapService", serviceName="SoapWS", portName="SoapWSPort")
public class SoapServiceImpl implements SoapService {
@RolesAllowed({"Boss"})
public SoapThing getSoapThing(String name, String prepend) throws SoapThingyException {
...
}
}
And the web.xml has this:
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>ApplicationRealm</realm-name>
</login-config>
I created a SoapHandler for the client, to add an Authorization header to the request, like this:
public boolean handleMessage(SOAPMessageContext context) {
try {
String credential = Base64.getEncoder().encodeToString((username+":"+password).getBytes("UTF-8"));
Map<String, Object> httpHeaders = null;
if (context.get(MessageContext.HTTP_REQUEST_HEADERS) != null) {
httpHeaders = (Map<String, Object>)context.get(MessageContext.HTTP_REQUEST_HEADERS);
} else {
httpHeaders = new HashMap<>();
}
httpHeaders.put("Authorization", Arrays.asList("Basic " + credential.substring(0, credential.length()-1)));
context.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
return true;
} catch (UnsupportedEncodingException e) {
return false;
}
}
My client is a standalone java app, using stubs generated with wsimport, and adds the handler to the BindingProvider:
SoapWS service = new SoapWS();
SoapService port = service.getSoapWSPort();
((BindingProvider)port).getBinding().setHandlerChain(Arrays.asList(new CredentialHandler("spike", "*****")));
SoapThing st = port.getSoapThingByNumber(1);
...it executes fine, adding the credentials to the Authorization header but I'm still getting an unauthorised response from the server:
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized
The webservice is deployed on Wildfly and the user is assigned to the ApplicationRealm, role Administator, groups Dog and Boss:
What am I missing?
Using basic authentication in a JAX-WS client is easier than that:
SoapWS service = new SoapWS();
SoapService port = service.getSoapWSPort();
Map<String,Object> requestContext = ((BindingProvider)port).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
SoapThing st = port.getSoapThingByNumber(1);
No handlers required.
The JAX-WS client machinery deals with the HTTP 401 challenge automatically.