// Create your client Client client = ....; // Or get it from your proxy Client client = ((XFireProxy) Proxy.getInvocationHandler(myClientProxy)).getClient(); client.setProperty(Channel.USERNAME, "username"); client.setProperty(Channel.PASSWORD, "pass");
去忘了写服务端应该怎么做,这个username和password该在那里验证呢??我翻遍了文档也没找着
来看第二条SOAP header authentication with JSR181,看起来倒是很简单
但是在Service的代码中每个方法里都要写一个UserToken验证的参数,虽然似乎权限粒度能控制得很细,但是这严重污染了业务逻辑的代码,非常的不优雅,放弃!
public void someOperation(String data, @WebParam(header=true) UserToken token) {
authenticate(token)
// do your normal request here
}
再看WS-Security,这是webservice的安全标准,但实在太复杂了,并且需要配置Service.xml,我们项目是Java1.5,Service.xml根本就没有写,是自动生成的,我是实在找不到Service.xml该在那配置?只好作罢
AuthenticationHandler需要修改一下,其他不用变:
AuthenticationHandler.java
import org.apache.log4j.Logger;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.handler.AbstractHandler;
import org.codehaus.xfire.fault.*;
import org.jdom.*;
public class AuthenticationHandler extends AbstractHandler {
private static final Logger log = Logger.getLogger(AuthenticationHandler.class);
public void invoke(MessageContext context) throws Exception {
log.info("authentication handler is invoked");
if (context.getInMessage().getHeader() == null)
{
throw new XFireFault("Request must include company authentication token.",
XFireFault.SENDER);
}
Element header = context.getInMessage().getHeader();
Element token = header.getChild("AuthenticationToken");
if (token == null)
{
throw new XFireFault("Request must include authentication token.",
XFireFault.SENDER);
}
String username = token.getChild("Username").getText();
String password = token.getChild("Password").getText();
try {
// 现在你已经得到了客户端传来的username和password,那就验证它吧(可以交给acegi来验证)
}
}catch(Exception e) {
log.warn(e);
throw new XFireFault("Authentication Failed.",
XFireFault.SENDER);
}
}
}
客户端代码: