使用 CXF 3.4.4
您可以像这样添加配置安全性的标头
<soapenv:Header>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">
<wsse:UsernameToken xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">
<wsse:Username>MY-USER</wsse:Username>
<wsse:Password Type="wsse:PasswordText">MY-PWD</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
使用拦截器,如下所述:http:
//cxf.apache.org/docs/ws-security.html
Client serviceClient = ClientProxy.getClient ( port );
Endpoint cxfEndpoint = serviceClient.getEndpoint ();
Map<String, Object> outProps = new HashMap<> ();
outProps.put ( WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN );
outProps.put ( WSHandlerConstants.USER, "MY-USER" );
outProps.put ( WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT );
outProps.put ( WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordCallback.class.getName () );
WSS4JOutInterceptor requestInterceptor = new WSS4JOutInterceptor ( outProps );
cxfEndpoint.getOutInterceptors ().add ( requestInterceptor );
MyRequest request = new MyRequest ();
Object [] res = serviceClient.invoke ( "operation-name", request );
MyResponse out = ( MyResponse ) res [0];
其中“操作名称”是要调用的 WebService 操作的名称
WSPasswordCallback 是:
import org.apache.wss4j.common.ext.WSPasswordCallback;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
public class ClientPasswordCallback implements CallbackHandler {
public void handle ( Callback [] callbacks ) throws IOException, UnsupportedCallbackException {
WSPasswordCallback passwordCallback = ( WSPasswordCallback ) callbacks [0];
// Set the password for our message.
passwordCallback.setPassword ( "MY-PWD" );
}
}