我使用 ininterceptor 注释解决了这个问题。我添加了 org.apache.cxf.interceptor.InInterceptors 注释并提供了自定义类来为 WSS4JInInterceptor 的必填字段设置值并将 WSS4JInInterceptor 添加到拦截器链中。
@InInterceptors(interceptors = {"com.xxx.xx.ws.wsse.WSSecurityInterceptor"})
@WebService
@Stateless
public class OrganizationImportServiceImpl{...enter code here
这是 com.xxx.xx.ws.wsse.WSSecurityInterceptor 类
package com.xxx.xx.ws.wsse;
import java.util.HashMap;
import java.util.Map;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
public class WSSecurityInterceptor extends AbstractPhaseInterceptor<Message>{
public WSSecurityInterceptor() {
super(Phase.PRE_PROTOCOL);
}
public WSSecurityInterceptor(String phase) {
super(Phase.PRE_PROTOCOL);
}
@Override
public void handleMessage(Message message) throws Fault {
Map<String, Object> props = new HashMap<String, Object>();
props.put("action", "UsernameToken");
props.put("passwordCallbackClass", "com.xxx.xx.ws.wsse.ServerPasswordCallback");
props.put("passwordType", "PasswordText");
WSS4JInInterceptor wss4jInHandler = new WSS4JInInterceptor(props);
message.getInterceptorChain().add((Interceptor<? extends Message>) wss4jInHandler);
}
}
然后在回调处理程序类中设置有效密码。这是回调处理程序类。
package com.xxx.xx.ws.wsse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
public class ServerPasswordCallback implements CallbackHandler {
private Map<String, String> passwords = new HashMap<String, String>();
public ServerPasswordCallback() {
super();
passwords.put("testuser", "testpwd");
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
if (pc.getIdentifier() == null) {
throw new IOException("authentication failure. required username password to proceed ..");
}
if (passwords.containsKey(pc.getIdentifier())) {
// set the password on the callback. This will be compared to the
// password which was sent from the client.
pc.setPassword(passwords.get(pc.getIdentifier()));
} else {
throw new IOException("authentication failure. invalid user name or password ");
}
}
}
然后在 cxf-rt-ws-security 模块中执行密码验证。