Spring 3.0.5 + CXF 2.4 + Hibernate 3.6.0 + MySQL 5.5 整合(CXF/Spring/Hibernate)实现简单的WSS4J认证 + 测试...

最近公司要做一个WebService项目,做了一个简单的例子,WebService认证使用的是简单的UsernameToken方式未使用X.509方式,DAO类大家自己去实现吧,这里就不得供了。

这里说明一下,在网上看到很多例子都是错误的,在WebService服务器端认证回调类中,应该是根据客户端传过来的用户名在数据库里查找到对应的密码在重新Set进去才可以正常的认证而不是直接在服务端进行get密码进行对比,因为WSS4J为了安全期间不允许直接在服务端直接get出来密码。

采用的全是最新的包,截图如下:

所有代码由于行数太多,所以默认为折叠代码,查看代码时请展开代码。

以下是配置文件:

applicationContext-common.xml:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd" default-lazy-init="true" default-autowire="byName"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/dataBaseCfg.properties</value> <value>classpath:/flowCollectionCfg.properties</value> </list> </property> </bean> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" p:jndiName="java:comp/env/jdbc/MySSH" /> --> <!-- BoneCP --> <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" p:driverClass="${jdbc.driver}" p:jdbcUrl="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" p:idleConnectionTestPeriodInMinutes="${idleConnectionTestPeriodInMinutes}" p:idleMaxAgeInMinutes="${idleMaxAgeInMinutes}" p:maxConnectionsPerPartition="${maxConnectionsPerPartition}" p:minConnectionsPerPartition="${minConnectionsPerPartition}" p:partitionCount="${partitionCount}" p:acquireIncrement="${acquireIncrement}" p:statementsCacheSize="${statementsCacheSize}" p:disableConnectionTracking="${disableConnectionTracking}" p:releaseHelperThreads="${releaseHelperThreads}" destroy-method="close" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingDirectoryLocations"> <list> <!-- <value>classpath:/cn/newlinetech/iCenter/userCenter/bo/</value> --> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop> <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop> <prop key="hibernate.order_updates">${hibernate.order_updates}</prop> <prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop> <prop key="hibernate.connection.isolation">${hibernate.connection.isolation}</prop> <!-- <prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop> --> <!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> --> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" /> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor" p:transactionManager-ref="transactionManager"> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="finish*">PROPAGATION_REQUIRED</prop> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="edit*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="remove*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop> </props> </property> </bean> <bean id="ProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" p:beanNames="*Service,*ServiceImpl" p:interceptorNames="transactionInterceptor" /> <bean id="wsServerAuthCallbackHandler" class="framework.system.AuthCallbackHandler.WsServerAuthCallbackHandler" scope="prototype" /> <bean id="wsClientAuthCallbackHandler" class="framework.system.AuthCallbackHandler.WsClientAuthCallbackHandler" scope="prototype" /> </beans>

applicationContext-webService.xml:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context" xmlns:cxf_jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf_jaxws="http://cxf.apache.org/jaxws" xmlns:cxf_core="http://cxf.apache.org/core" xmlns:cxf_security="http://cxf.apache.org/configuration/security" xmlns:cxf_http="http://cxf.apache.org/transports/http/configuration" xmlns:cxf_wsa="http://cxf.apache.org/ws/addressing" xmlns:cxf_policy="http://cxf.apache.org/policy" xmlns:cxf_soap="http://cxf.apache.org/bindings/soap" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/policy http://cxf.apache.org/schemas/policy.xsd http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd"> <!--Basic WebService CXF ConfigFile--> <import resource="classpath*:/META-INF/cxf/cxf.xml" /> <import resource="classpath*:/META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath*:/META-INF/cxf/cxf-extension-jaxrs-binding.xml" /> <import resource="classpath*:/META-INF/cxf/cxf-servlet.xml" /> <!-- Ws-Service --> <cxf_jaxws:endpoint id="iCenterFlowCollectionServer" implementor="cn.newlinetech.FlowCollectionServer.main.impl.FlowCollectionServer" address="/flowCollectionService"> <cxf_jaxws:inInterceptors> <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> <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="PasswordDigest" /> <entry> <key> <value>passwordCallbackRef</value> </key> <ref bean="wsServerAuthCallbackHandler" /> </entry> </map> </constructor-arg> </bean> </cxf_jaxws:inInterceptors> </cxf_jaxws:endpoint> <!-- Ws-Client --> <cxf_jaxws:client id="flowCollectionService" address="http://${flowCollectionServerIP}:${flowCollectionServerPort}/FlowCollectionServer/WebServices/flowCollectionService" serviceClass="cn.newlinetech.wsClient.IFlowCollectionServer"> <cxf_jaxws:outInterceptors> <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> <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="user" value="admin" /> <entry key="passwordType" value="PasswordDigest" /> <entry> <key> <value>passwordCallbackRef</value> </key> <ref bean="wsClientAuthCallbackHandler" /> </entry> </map> </constructor-arg> </bean> </cxf_jaxws:outInterceptors> </cxf_jaxws:client> </beans>

MySQL配置(连接池配置 dataBaseCfg.properties):

#MySQL配置 hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #hibernate.dialect=org.hibernate.dialect.MySQL5Dialect #hibernate.dialect=org.hibernate.dialect.MySQLDialect jdbc.url=jdbc:mysql://localhost:3306/DB_NewLine_iCenter?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull jdbc.driver=com.mysql.jdbc.Driver jdbc.username=mysql jdbc.password=mysql hibernate.show_sql=false hibernate.format_sql=false hibernate.use_sql_comments=false hibernate.cache.use_second_level_cache=false hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider hibernate.hbm2ddl.auto=update hibernate.order_updates=true hibernate.jdbc.batch_size=30 hibernate.jdbc.fetch_size=100 hibernate.max_fetch_depth=2 hibernate.connection.autocommit=true hibernate.connection.isolation=1 #Hibernate3.0的查询翻译器: hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory #Hibernate2.1的查询翻译器 #hibernate.query.factory_class=org.hibernate.hql.classic.ClassicQueryTranslatorFactory minPoolSize=5 maxPoolSize=20 maxIdleTime=1800 idleConnectionTestPeriodInMinutes=240 maxStatements=0 idleMaxAgeInMinutes=240 maxConnectionsPerPartition=30 minConnectionsPerPartition=5 partitionCount=3 acquireIncrement=5 statementsCacheSize=50 releaseHelperThreads=2 disableConnectionTracking=true

WebService 客户端配置文件(flowCollectionCfg.properties):

#WebService服务器地址 flowCollectionServerIP=192.168.1.8 #WebService服务器端口 flowCollectionServerPort=8080

web.xml(<display-name>节点自行设置):

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>XXXXX</display-name> <session-config> <session-timeout>30</session-timeout> </session-config> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-config/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>flushMode</param-name> <param-value>AUTO</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/WebServices/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/WEB-INF/errorPage/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/errorPage/500.jsp</location> </error-page> </web-app>

WsServerAuthCallbackHandler.java:

package framework.system.AuthCallbackHandler; 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; /** * * <p>Copyright: All Rights Reserved</p> * <p>Company: 北京新线科技发展有限公司 http://www.NewLineTech.cn</p> * <p>Description: Ws服务器端认证回调类 </p> * @author:Eric */ public class WsServerAuthCallbackHandler implements CallbackHandler{ @Override public void handle(Callback[] callbacks) throws IOException,UnsupportedCallbackException{ WSPasswordCallback wspc = (WSPasswordCallback) callbacks[0]; if(wspc.getIdentifier().equals("admin")){ try{ wspc.setPassword("newline"); }catch(Exception e){ throw new SecurityException("用户名密码错误"); } }else{ throw new SecurityException("无此用户"); } } }

WsClientAuthCallbackHandler.java:

package framework.system.AuthCallbackHandler; 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; /** * * <p>Copyright: All Rights Reserved</p> * <p>Company: 北京新线科技发展有限公司 http://www.NewLineTech.cn</p> * <p>Description: WS客户端认证回调类</p> * @author:Eric */ public class WsClientAuthCallbackHandler implements CallbackHandler{ @Override public void handle(Callback[] callbacks) throws IOException,UnsupportedCallbackException{ for(int i = 0;i < callbacks.length;i ++ ){ WSPasswordCallback wspc = (WSPasswordCallback) callbacks[i]; int usage = wspc.getUsage(); if(usage == WSPasswordCallback.USERNAME_TOKEN){ wspc.setPassword("newline"); wspc.setIdentifier("admin"); } } } }

WsTest.java (单元测试):

package JUnitTest; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import cn.newlinetech.wsClient.IFlowCollectionServer; /** * * <p>Copyright: All Rights Reserved</p> * <p>Company: 北京新线科技发展有限公司 http://www.NewLineTech.cn</p> * <p>Description: 单元测试类 </p> * @author:Eric */ @ContextConfiguration(locations = {"classpath:/spring-config/applicationContext-*.xml"}) public class WsTest extends AbstractTransactionalJUnit4SpringContextTests{ @Autowired private IFlowCollectionServer flowCollectionService; @Test public void testFlowCollectionService(){ System.out.println(flowCollectionService.sayHello2("eric","25")); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值