基于Filter过滤器实现权限控制
一、前言
最近项目在上线后,客户请了第三方来对项目进行安全性检查,暴露出了项目里的很多漏洞,比如说纵向越权访问(普通用户角色可以直接通过链接的形式获取到业务处理后返回的数据),这样客户瞬间慌了,找到leader让紧急修复。第三方也给出了相应的建议:通过Spring Security配置基于角色进行权限管理 。但是项目本身使用了Shiro 来进行权限管理。因此最后采用了Shiro来进行限制纵向越权访问。做完项目以后我就想能不能通过Filter来实现对用户的纵向越权访问进行限制。(说干就干,干之前先来简单的看看Filter的相关内容)
二、Filter 过滤器介绍
1.简介
Filter即过滤器,它是Servlet技术中最激动人心的技术之一,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp,Servlet, 静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,Filter接口源代码:
public abstract interface Filter{
public abstract void init(FilterConfig paramFilterConfig) throws ServletException;//初始化
public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) throws IOException, ServletException;// 拦截逻辑
public abstract void destroy();//销毁
}
2.Filter的工作原理
Filter接口中有一个doFilter方法,当我们编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:
- 调用目标资源之前,让一段代码执行。
- 是否调用目标资源(即是否让用户访问web资源)。
- 调用目标资源之后,让一段代码执行。
- web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
3.Filter的生命周期
- Filter的创建
Filter的创建和销毁由web服务器负责。 web应用程序启动时,web服务器将创建Filter的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作,filter对象只会创建一次,init方法也只会执行一次。通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。 - Filter的销毁
web容器调用destroy方法销毁Filter。destroy方法在Filter的生命周期中仅执行一次。在destroy方法中,可以释放过滤器使用的资源。 - FilterConfig接口
用户在配置filter时,可以使用为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了
filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得:
String getFilterName():得到filter的名称。
String getInitParameter(String name): 返回在部署描述中指定名称的初始化参数的值。如果不存在返回null.
Enumeration getInitParameterNames():返回过滤器的所有初始化参数的名字的枚举集合。
public ServletContext getServletContext():返回Servlet上下文对象的引用。
4.Filter开发流程
- 编写java类实现Filter接口,并实现其doFilter方法。
public class XXXXFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
}
public void init(FilterConfig arg0) throws ServletException {
}
}
- 在web. xml中配置过滤器(基于Spring):
<filter>
<filter-name>powerCheckingFilter</filter-name>
<filter-class>com.datadriver.web.common.filter.PowerCheckingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>powerCheckingFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
三、业务实现
1.思路:
- 首先,既然是通过拦截器来进行操作权限管理,那么我们就需要创建一个拦截器(PowerCheckingFilter)用来过滤掉所有请求。
- 获取登录用户的角色。
- 设定各个角色需要控制的URL(这里采用配置文件的形式)。
- 由于并不是要拦截掉所有的请求,所以这里我采用黑名单的逻辑,即,只要是配置文件中有的URL一律干掉,其他的直接放行。
- 编写配置文件(blacklist.properties)。
- 在PowerCheckingFilter 中预处理配置文件(即读出配置文件的内容)。
- 在PowerCheckingFilter 中重写init()、doFilter()、destroy()方法,在doFilter()中实现具体的业务逻辑。
2.代码
PowerCheckingFilter:
/**
*
* <p> 用户权限配置模块 目前只对普通用户进行拦截处理</p>
* @author fritain
* @date 2019/6/14
*/
@WebFilter(filterName = "PowerCheckingFilter")
public class PowerCheckingFilter implements Filter {
protected static String name;
protected static String word;
protected static String url;
protected static String publicKey ;
protected static Properties pro=PropertyReader.getproperty("blacklist.properties");
protected static Boolean powerFlag;
private static final String NORMAL = "NORMAL";
static {
publicKey = ResourceBundle.getBundle("application").getString("jdbc.publicKey");
url = ResourceBundle.getBundle("application").getString("jdbc.url");
try {
name = ConfigTools.decrypt(publicKey,ResourceBundle.getBundle("application").getString("jdbc.username"));
word = ConfigTools.decrypt(publicKey,ResourceBundle.getBundle("application").getString("jdbc.password"));
} catch (Exception e) {
e.printStackTrace();
}
powerFlag = Boolean.valueOf(pro.getProperty("blackList.checkPower", "false"));
}
@Override
public void destroy() {
UnitedLogger.debug("PowerCheckingFilter:权限过滤器开始销毁...");
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
UnitedLogger.debug("PowerCheckingFilter:权限过滤器启动...");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (isIntercept(request)) {
UnitedLogger.debug("PowerCheckingFilter:权限过滤器开始执行...");
HttpSession session = request.getSession();
// Perform actions: Get logged-in user information
SystemUser userInfo = (SystemUser) session.getAttribute(SessionAttribute.USERINFO);
// Get the role information of the logged-in user
String roleName = getRoleName(userInfo.getUserId());
UnitedLogger.error("---------"+roleName);
// Get the current request resource path
String requestUrl = getPath(request);
UnitedLogger.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + requestUrl);
String[] blackListUrl = new String[]{};
if (NORMAL.equals(roleName)){
// Read the blacklist of the corresponding roles
UnitedLogger.error("读取配置文件...");
String url = pro.getProperty("NORMAL.balackList.url", "");
UnitedLogger.error("<<<<<<<<<<<<<<<URL:"+url);
if (url!=null&&!"".equals(url.trim())){
blackListUrl = url.split(",");
if (checkBlackLists(requestUrl,blackListUrl)){
UnitedLogger.error("当前请求处于黑名单,重定向...");
FilterUtil.sendMessage(request,response,401);
}
}
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
UnitedLogger.debug("PowerCheckingFilter:权限过滤器开始初始化...");
}
private String getRoleName(String id){
// declare Connection and Statement objects
Connection connection = null;
Statement statement = null;
String resultStr = null;
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
connection = DriverManager.getConnection(url,name,word);
// create a Statement object
statement = connection.createStatement();
// create a SQL String
String sqlText = "select VC_ROLECODE FROM sys_role sr,sys_user_role sur WHERE sr.f_roleid = sur.f_roleid and sur.f_userid='"+id+"'";
// Perform operations
ResultSet result = statement.executeQuery(sqlText);
while (result.next()){
resultStr = result.getString("VC_ROLECODE");
}
} catch (SQLException e) {
e.printStackTrace();
}
return resultStr;
}
private Boolean checkBlackLists(String uri,String[] arr){
if (uri==null||uri.isEmpty()){
return false;
}
Boolean flag = false;
for (String s : arr) {
if ((uri.toLowerCase()).equals(s.trim().toLowerCase())){
flag = true;
break;
}
}
return flag;
}
private String getPath(HttpServletRequest request){
//获取项目名
String projectName = request.getContextPath();
//获取当前完整请求路径
String requestURL = request.getRequestURL().toString();
//以项目名为界分割完整请求路径
String[] pathUrl = requestURL.split(projectName);
return pathUrl[1];
}
private Boolean isIntercept(HttpServletRequest request){
Boolean flag = powerFlag;
if (getPath(request).contains("login.do")||getPath(request).endsWith("loginPage.do")||getPath(request).contains("login")){
flag = !flag;
}
return flag;
}
}
blacklist.properties
#权限校验开关
blackList.checkPower=true
# 系统管理员黑名单
MANAGER_SYS.balackList.url =
# 机构管理员黑名单
MANAGER_COMPANY.balackList.url =
# 普通用户黑名单
NORMAL.balackList.url = /rest/dept/deptList.do,/rest/dept/doDeptZtree.do,/rest/dept/deptAdd.do,/rest/dept/doDeptAdd.do\ ,/rest/user/doUserList.do,/rest/user/userAdd.do,/rest/user/doUserAdd.do,/rest/user/userList.do,/rest/user/doCheckUserNo.do,/rest/user/doCheckAccount.do\
,/rest/menu/menumanage.do\
,/rest/role/roleList.do,/rest/role/roleEdit.do,/rest/role/doRoleEdit.do\
web.xml 中的配置
<filter>
<filter-name>powerCheckingFilter</filter-name>
<filter-class>com.datadriver.web.common.filter.PowerCheckingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>powerCheckingFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>