在请求的方法中访问SOAP消息头

时间:2013-08-30 13:47:08

标签: java web-services soap jax-ws handler

编辑:消息已清除且代码已添加

我使用基本的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());
    }
}

非常感谢

1 个答案:

答案 0 :(得分:3)

最后,我找到了我正在搜索的内容:

Follow this link.

在“将处理程序级别的信息传递给应用程序”部分