原文链接 http://www.zhaochao.net/index.php/2016/01/26/12/
配置原因
随着业务的发展项目会变的越来越多,项目需要进行模块化与服务化,服务化中常用的方法就是使用RPC技术,Hessian就是常用的一种RPC技术。之前用过Hessian,没有考虑太多,只是用用,最近想了想Hessina没有安全验证,将URL发部到网上后,只要别人知道你的URL,再知道你的方法,他就可以调用了,这样感觉不太安全,于是找了一下方法,给Hessian增加权限我所知道的有两种,一种是通过额外的代码去验证,另一种是Hessian自带的权限验证,主要是将用户名和密码增加到http 响应头在,部分源码如下所示:
/**
* Method that allows subclasses to add request headers such as cookies.
* Default implementation is empty.
*/
protected void addRequestHeaders(HessianConnection conn)
{
conn.addHeader("Content-Type", "x-application/hessian");
conn.addHeader("Accept-Encoding", "deflate");
String basicAuth = _factory.getBasicAuth();
if (basicAuth != null)
conn.addHeader("Authorization", basicAuth);
}
public String getBasicAuth()
{
if (_basicAuth != null)
return _basicAuth;
else if (_user != null && _password != null)
return "Basic " + base64(_user + ":" + _password);
else
return null;
}
在tomcat中配置服务url的访问用户名和密码,具体做法如下
- 在服务端的web.xml中为hessan的url增加权限验证代码如下:
<!-- 定义hessian认证 -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Hessian Security</web-resource-name>
<url-pattern>/api/service/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Hessian</role-name>
</auth-constraint>
</security-constraint>
<!-- Define the Login Configuration for this Application -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Hessian Security</realm-name>
</login-config>
<!-- Security roles referenced by this web application -->
<security-role>
<description></description>
<role-name>Hessian</role-name>
</security-role>
- 在tomcat 的tomcat-users.xml中增加 用户名和密码
<role rolename="Hessian"/>
<user username="zhaochao" password="zhaochao" roles="Hessian"/>
- hessian客户端增加用户名和密码
hessian自带客户端
HVideoService videoClient = (HVideoService) factory.create(HVideoService.class, url);
factory.setUser("zhaochao");
factory.setPassword("zhaochao");
spring客户端
<bean id="videoClient" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="${baseUrl}/api/service/videoExporter" />
<property name="serviceInterface" value="com.***" />
<property name="overloadEnabled" value="true" />
<property name="username" value="zhaochao"></property>
<property name="password" value="zhaochao"></property>
</bean>