JAX-WS Request with Basic Authentication

lesnar :

i am trying to call a SOAP Webservice using handlers with Basic Authorization but somehow API is responding with 401 unauthorized.

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outboundProperty.booleanValue()) {
        String authString = parameter.getUser() + ":" + parameter.getPassword();
        try {
             Map<String, List<String>> headers = (Map<String, List<String>>)
                     context.get(MessageContext.HTTP_REQUEST_HEADERS);

             if (null == headers) {
                 headers = new HashMap<String, List<String>>();
             }

             headers.put("Authorization", Collections.singletonList(
                 "Basic " + new String(Base64.encode(authString.getBytes()))));
        } catch(Exception e) {
            log4j.error(e.getMessage(), e);
        }
    }
    return outboundProperty;
}

When i use SOAP UI and manually add the Authorziation Header (value from code during debug) then i recieve response from the Endpoint but using code it fails as of now.

Any pointers would be really helpful. Thanks

Spara :

You would need to change your code to like this:

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if(outboundProperty.booleanValue()){
        try{
            String authString = parameter.getUser() + ":" + parameter.getPassword();
            SOAPMessage soapMessage =context.getMessage();
            String authorization = new sun.misc.BASE64Encoder().encode(authString.getBytes());
            soapMessage.getMimeHeaders().addHeader("Authorization","Basic " + authorization);   
            soapMessage.saveChanges(); 
        }catch(Exception e){
            log4j.error(e.getMessage(), e);
        }
    }
    return true;
}

Updated:

As explained here you should use Base64Coder from sun.misc.BASE64Encoder() for encoding authString

Also you should always return true from this method otherwise you will block processing of the handler request chain by returning false.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102632&siteId=1