具有基本身份验证的JAX-WS请求



我试图使用具有基本授权的处理程序调用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;
}

更新:

正如这里所解释的,您应该使用sun.misc.BASE64Encoder()中的Base64Coder来编码authString

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

最新更新