3

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

alexandroid
  • 1,469
  • 2
  • 15
  • 32
lesnar
  • 2,400
  • 7
  • 41
  • 72
  • did you tried my updated answer bro? – Mohsen Dec 07 '18 at 17:22
  • @Spara using BASE64Encoder() from sun misc did not help me. – lesnar Dec 10 '18 at 07:35
  • Did you tried to return `true` instead of returning `outboundProperty`? – Mohsen Dec 10 '18 at 09:03
  • What happened bro? could you solve the problem? The bounty will disappear in 2 days – Mohsen Dec 15 '18 at 12:31
  • please check https://stackoverflow.com/questions/7071366/java-web-service-client-basic-authentication or https://stackoverflow.com/questions/2322953/jax-ws-adding-soap-headers/36847739#36847739 Im sure you can find the problem – Mohsen Dec 16 '18 at 23:30

1 Answers1

2

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.

Mohsen
  • 4,536
  • 2
  • 27
  • 49