编辑:清除消息并添加代码
我使用基本的 Java 客户端开发了一个基于 jax-ws 的 Web 服务。
我使用 SOAP 处理程序对用户进行身份验证。一个在客户端将 userId 和令牌添加到 SOAP 标头,另一个在服务器端获取这些信息并使用数据库对用户进行身份验证。
客户端(简化):
import static modules.auth.AuthClient.userID;
import static modules.auth.AuthClient.token;
public boolean handleMessage(SOAPMessageContext context) {
//Getting SOAP headers
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
QName qname;
SOAPHeaderElement soapHeaderElement;
//Add userID in SOAP header
qname = new QName("****","UserID");
soapHeaderElement = soapHeader.addHeaderElement(qname);
soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
soapHeaderElement.addTextNode(userID);
//Add token in SOAP header
qname = new QName("****","Token");
soapHeaderElement = soapHeader.addHeaderElement(qname);
soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
soapHeaderElement.addTextNode(token);
soapMsg.saveChanges();
return true;
}
服务器端(简化):
public boolean handleMessage(SOAPMessageContext context) {
Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!isRequest) {
//Getting SOAP headers
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
Iterator it = soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);
Node userIDNode = (Node) it.next();
String userID = (userIDNode == null) ? null : userIDNode.getValue();
Node tokenNode = (Node) it.next();
String token = (tokenNode == null) ? null : tokenNode.getValue();
//Return if the user is connected
User u = AuthWS.validToken(userID, token);
//Here I have my user but I don't know how to get it in my requested method
}
return true;
}
为了管理用户权限,我想直接以请求的方法访问我的用户。
可以请求的方法示例:
public Project getProject(@WebParam(name = "name") String name) throws WebServiceFailure, EntityNotFoundException {
//Here I would like to verify the user's rights
try {
PreparedStatement ps = DBConnect.getStatement("SELECT name FROM projects WHERE name = '" + name + "'");
ResultSet res = ps.executeQuery();
if(res.next()){
Project p = new Project(res.getString("name"));
ps.close();
return p;
} else {
ps.close();
throw new EntityNotFoundException("Can't find the project '"+name+"'");
}
} catch (SQLException ex) {
throw new WebServiceFailure(ex.getMessage());
}
}
非常感谢