简体   繁体   中英

JAX-WS Request with Basic Authentication

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM