【问题标题】:JAX-WS Request with Basic Authentication具有基本身份验证的 JAX-WS 请求
【发布时间】:2019-05-09 11:04:25
【问题描述】:

我正在尝试使用具有基本授权的处理程序调用 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 并手动添加授权标头(调试期间代码中的值)时,我会收到来自端点的响应,但使用代码它现在失败了。

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

【问题讨论】:

标签: java web-services soap jax-ws


【解决方案1】:

你需要把你的代码改成这样:

@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

此外,您应该始终从此方法返回 true,否则您将通过返回 false 来阻止处理程序请求链的处理。

【讨论】:

  • 您能否突出显示实际更改并提供解释?
猜你喜欢
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多