webservice安全之WS-Security验证

时间:2023-01-13 09:40:41


WebService有两种安全机制,一是利用WS-Security将签名和加密头加入SOAP消息,另一个是利用数字证书和数字签

名认证。此篇文章介绍利用cxf实现WS-Security验证。

首先,服务器端配置

利用webservice和jms实现系统间的数据同步之一介绍的项目中添加:


package com.test.auth;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class ServerPasswordCallback implements CallbackHandler
{

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
WSPasswordCallback pc = (WSPasswordCallback)callbacks[0];

if(pc.getIdentifier().equals("admin"))
{
pc.setPassword("password");
}
else
{
throw new UnsupportedCallbackException(pc, "check failed");
}
}

}

修改spring文件:


 

<!-- 发布ws,其中address的此ws名称 -->
<jaxws:endpoint id="user" implementor="com.test.UserServiceImpl" address="/user">
<jaxws:inInterceptors>
<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken" />
<entry key="passwordType" value="PasswordText" />
<entry key="user" value="cxfServer" />
<entry key="passwordCallbackRef">
<ref bean="serverPasswordCallback" />
</entry>
</map>
</constructor-arg>
</bean>
</jaxws:inInterceptors>
</jaxws:endpoint>

<bean id="serverPasswordCallback" class="com.test.auth.ServerPasswordCallback"/>


 其次,客户端配置如下,在用webservice和jms实现系统间的数据同步之二介绍的项目中添加:

增加ClientPasswordCallback类:

package com.test.auth;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class ClientPasswordCallback implements CallbackHandler
{

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for(Callback cb : callbacks)
{
WSPasswordCallback pc = (WSPasswordCallback)cb;
pc.setIdentifier("admin");
pc.setPassword("password");
}
}

}

修改spring文件:

<!-- webserice接收客户端 -->
<jaxws:client id="userService"
address="http://10.78.194.92:8088/webserviceserver/service/user"
serviceClass="com.test.UserService">
<jaxws:outInterceptors>
<bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" />
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken" />
<entry key="passwordType" value="PasswordText" />
<entry key="user" value="cxfClient" />
<entry key="passwordCallbackRef">
<ref bean="clientPasswordCallback"/>
</entry>
</map>
</constructor-arg>
</bean>
</jaxws:outInterceptors>
</jaxws:client>

<bean id="clientPasswordCallback" class="com.test.auth.ClientPasswordCallback"/>


完毕。