我正在用apache cxf创建一个jax-ws客户端。 我在使用spring cotext配置时遇到了困难。 我只需要将此标题添加到我的肥皂请求中:
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="usernametoken">
<wsse:Username>login</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
我有三个参数:usernametoken,password,login。
<jaxws:client id="***" name="***"
endpointName="***"
serviceName="***"
address="***"
serviceClass="***"
username="***"
password="***"
xmlns:tns="***">
</jaxws:client>
上面的代码工作并发送soap消息,但没有安全头! 你能给我一些如何添加标题的想法吗?
答案 0 :(得分:3)
使用此配置
<jaxws:client etc...>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken"/>
<entry key="user" value="login"/>
<entry key="passwordType" value="PasswordText"/>
<entry key="passwordCallbackRef" value-ref="myPasswordCallback"/>
</map>
</constructor-arg>
</bean>
</jaxws:outInterceptors>
</jaxws:client>
<bean id="myPasswordCallback" class="client.ClientPasswordCallback"/>
这个类来管理密码
public class ClientPasswordCallback implements CallbackHandler {
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
if ("login".equals(pc.getIdentifier())) {
pc.setPassword("thepassword");
} // else {...} - can add more users, access DB, etc.
}
}
如果您更喜欢Java代码,也可以
Client client = ClientProxy.getClient(port);
Endpoint cxfEndpoint = client.getEndpoint();
Map<String,Object> outProps = new HashMap<String,Object>();
outProps.put("action", "UsernameToken");
outProps.put("user", "login");
outProps.put("passwordType","PasswordText");
ClientPasswordCallback c = new ClientPasswordCallback();
outProps.put("passwordCallbackRef",c);
WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
cxfEndpoint.getOutInterceptors().add(wssOut);
答案 1 :(得分:2)
您需要使用CXF拦截器添加安全标头。
所以你基本上需要从cxf-security定义一个新的拦截器bean(WSS4JOutInterceptor)并将正确的键值作为输入传递给它的构造函数:
<bean id="fooSecurityOutInterceptor" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<constructor-arg>
<map>
[...]
</map>
</constructor-arg>
</bean>
请注意,http://cxf.apache.org/docs/ws-security.html中记录了这一点,但您可能需要查看org.apache.ws.security.handler.WSHandlerConstants的源代码以获取所有可能的键(在您的情况下,请查看USERNAME_TOKEN, PASSWORD_TYPE ...)并将您的值注入此bean中的相应键。
然后,您只需将此bean作为out拦截器分配给您的jaxws-client bean。
<jaxws:client id="***" name="***" endpointName="***" serviceName="***" address="***" serviceClass="***" xmlns:tns="***">
<jaxws:outInterceptors>
<ref bean="fooSecurityOutInterceptor" />
</jaxws:outInterceptors>
</jaxws:client>
这应该可以解决问题。 您可以添加第二个拦截器,如org.apache.cxf.interceptor.LoggingOutInterceptor,以检查是否添加了标头以稍微调整键/值。