axis2客户端基于ws-security用户令牌验证访问

如果服务端使用了ws-security进行用户验证时,客户端访问时需要在报文头部添加用户名和密码,用户令牌验证只允许在报文头部添加验证。采用axis2生成java代码,以下为实现代码:
  
//stub为生成的代码
stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,"http:.....?wsdl");
//安全头报文生成
SOAPHeaderElement sl = setSoapHeader();
stub.setHeader(sl);

stub.method(arg0, arg1);


private static SOAPHeaderElement setSoapHeader() throws ParserConfigurationException{
// create document of w3c
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
// create Element
String address= "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
Element security = document.createElementNS("namespace", "Security");
security.setAttribute("xmlns:wsse", address);
Element usernameToken = document.createElementNS("namespace", "UsernameToken");
Element username = document.createElementNS("namespace", "Username");
Element password = document.createElementNS("namespace", "Password");
password.setAttribute("Type",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
// add Element
usernameToken.appendChild(username);
usernameToken.appendChild(password);
security.appendChild(usernameToken);
// set value
Text usernameValue = document.createTextNode("aaaa");
username.appendChild(usernameValue);
Text passwordValue = document.createTextNode("aaaa");
password.appendChild(passwordValue);
// create SOAPHeaderElement
SOAPHeaderElement ppElement = new SOAPHeaderElement(security);
ppElement.setPrefix("wsse");
return ppElement;
}

你可能感兴趣的:(webservice)