我想使用WS-Security來保護我的Web服務。我使用CXF來公開我的端點,並使用Java代碼(又稱爲CXF代碼優先服務)生成WSDL。CXF生成的WSDL不包含WS-SecurityPolicy定義
本教程介紹瞭如何使用WS-Security與CXF在WSDL手動管理:http://www.ibm.com/developerworks/java/library/j-jws13/index.html
不過,我使用CXF自動生成WSDL。 生成的WSDL並不表示客戶端應該使用WS-Security。我希望在WSDL與此類似:
<wsp:Policy wsu:Id="UsernameToken" xmlns:wsu=
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding/>
<sp:SupportingTokens>
<wsp:Policy>
<sp:UsernameToken sp:IncludeToken=".../IncludeToken/AlwaysToRecipient"/>
</wsp:Policy>
</sp:SupportingTokens>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
我沒有使用Spring,但我用一個嵌入式碼頭。這裏是我如何接線的一切:
CXFNonSpringServlet cxfServlet = new CXFNonSpringServlet() {
private static final long serialVersionUID = 1L;
@Override
protected void loadBus(ServletConfig sc) {
super.loadBus(sc);
Map<String, Object> inProps = new HashMap<String, Object>();
inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
inProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
inProps.put(WSHandlerConstants.PW_CALLBACK_REF, new TestCallback());
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setBus(bus);
factory.setServiceBean(new MyServiceEndpointImpl());
factory.setAddress("/myservice");
factory.getInInterceptors().add(new WSS4JInInterceptor(inProps));
factory.create();
}
};
Server server = new Server(8080);
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
ServletContextHandler rootContext = new ServletContextHandler(contexts, "/");
rootContext.addServlet(new ServletHolder(cxfServlet), "/soap/*");
server.start();