JAX-WS 使用基本身份验证的请求

JAX-WS Request with Basic Authentication

我正在尝试使用具有基本授权的处理程序调用 SOAP Web 服务,但不知何故 API 以 401 未授权响应。

@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;
}

当我使用 SOAP UI 并手动添加 Authorziation Header(调试期间代码中的值)时,我收到了端点的响应,但使用代码它现在失败了。

任何指点都会很有帮助。谢谢

您需要将代码更改为如下所示:

@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;
}

已更新:

here 所述,您应该使用 sun.misc.BASE64Encoder() 中的 Base64Coder 来编码 authString

此外,您应该始终使用此方法 return true,否则您将通过 returning false.

阻止处理程序请求链的处理