当前位置:   article > 正文

用户权限管理之权限过滤_wpf 权限过滤器

wpf 权限过滤器

1.前言

  之前有写过一篇小记,当时的用户权限管理十分简陋,只通过判断角色名来进行权限控制.属于0.5版本的权限管理.现在,在用户权限管理模块中,除了之前的用户表,角色表,权限表,日志表4大主表外(还有关联表),又增加了url资源表和行为表.为此,之前的low版本的权限管理不可用了,需要一个新的细粒度的权限过滤.


2.思路

  最初的设想是url资源表和行为表中存储对应请求需要的权限,权限管理过滤器则对请求的url和用户拥护的权限去数据库中匹配,符合条件则通过,不符合则跳转无权限页面.
不过考虑到访问页面的频繁和ajax请求的频繁度,这样的做法会提高数据库的压力.由于url资源表和行为表的数据相对较少,所以考虑在项目启动时将信息存储在内存.这样既提高了速度,又减轻了数据库的压力.由于将数据存在了内存中,当数据库的信息修改时就存在了数据不一致的问题,对此我编写了一个管理类来处理这个问题.

3.代码

3.1 URLRoleFilter.java

  1. public class URLRoleFilter implements Filter {
  2. private String redirectPage;
  3. private String unCheckURL;
  4. @Override
  5. public void destroy() {
  6. }
  7. @Override
  8. public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
  9. throws IOException, ServletException {
  10. HttpServletRequest request = (HttpServletRequest) req;
  11. HttpServletResponse response = (HttpServletResponse)resp;
  12. String servletPath = request.getServletPath();
  13. String requestMethod = request.getMethod();
  14. String requestType = request.getHeader("X-Requested-With");
  15. List<String> unCheckList = Arrays.asList(unCheckURL.split(","));
  16. if(null!=unCheckList && unCheckList.contains(servletPath)) {
  17. chain.doFilter(request, response);
  18. return;
  19. }
  20. UserLoginInfoModel userLogin = SessionUtil.getUserLogin(request);
  21. String roleId = userLogin.getRoleId()==null?"":userLogin.getRoleId();
  22. //当前用户无任何角色,且不是注销操作时,跳转无权限页面
  23. if(StringX.isEmpty(roleId)) {//&& !servletPath.contains("/security/signOut.do")
  24. if(!StringX.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {//ajax请求
  25. JSONObject result = new JSONObject();
  26. result.accumulate("success", false);
  27. result.accumulate("errUrl", request.getContextPath() + redirectPage);
  28. try {
  29. response.getWriter().print(result.toString());
  30. } catch (IOException e) {
  31. ARE.getLog().error(e);
  32. }
  33. }
  34. else if("POST".equals(requestMethod)) {
  35. response.setStatus(302);//临时定向响应码
  36. response.setHeader("Location", request.getContextPath() + redirectPage);//代表转向的地址
  37. }
  38. else {
  39. response.sendRedirect(request.getContextPath() + redirectPage);
  40. }
  41. return;
  42. }
  43. if(!UrlAndActionManager.getInstence().match(servletPath, userLogin)) {//权限匹配不通过
  44. if(!StringX.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {//ajax请求
  45. JSONObject result = new JSONObject();
  46. result.accumulate("success", false);
  47. result.accumulate("errUrl", request.getContextPath() + redirectPage);
  48. try {
  49. response.getWriter().print(result.toString());
  50. } catch (IOException e) {
  51. ARE.getLog().error(e);
  52. }
  53. }
  54. else if("POST".equals(requestMethod)) {
  55. response.setStatus(302);//临时定向响应码
  56. response.setHeader("Location", request.getContextPath() + redirectPage);//代表转向的地址
  57. }
  58. else {
  59. response.sendRedirect(request.getContextPath() + redirectPage);
  60. }
  61. return;
  62. }
  63. chain.doFilter(request, response);
  64. }
  65. @Override
  66. public void init(FilterConfig cfg) throws ServletException {
  67. ServletContext context = cfg.getServletContext();
  68. redirectPage = context.getInitParameter("noRolePage");
  69. unCheckURL = context.getInitParameter("unCheckURL");
  70. }
  71. }

  这是过滤器的代码,基本上就是之前的版本,只是在进行权限判断的时候,不通过角色来判断,而是使用了一个管理类来判断.一般情况下这个管理类就是从内存中来比较权限的.

3.2 InitUrlAndActionManagerServlet.java

  1. public class InitUrlAndActionManagerServlet extends HttpServlet {
  2. private static final long serialVersionUID = 1L;
  3. public void init(ServletConfig config) throws ServletException {
  4. ARE.getLog().info("资源权限管理器初始化开始");
  5. UrlAndActionManager.getInstence();
  6. ARE.getLog().info("资源权限管理器初始化完成");
  7. }
  8. }

这个类的作用是在项目启动后把url资源表数据和行为表数据加载到内存中(在web.xml中配置一下优先级).

3.3 UrlAndActionManager.java

  1. public class UrlAndActionManager extends Thread{
  2. private ReadWriteLock lock; //读写锁
  3. private boolean updateFlag; //管理类map是否正在更新 标志位
  4. private Map<String,String> urlMap; //存放url表数据
  5. private Map<String,String> actionMap; //存放行为表数据
  6. private UrlDao urlDao; //url表操作类
  7. private ActionDao actionDao; //行为表操作类
  8. private boolean dbChangeFlag; //数据库信息是否改变 标志位
  9. private static class UrlAndActionManagerHolder{
  10. private static final UrlAndActionManager INSTANCE = new UrlAndActionManager();
  11. }
  12. private UrlAndActionManager(){
  13. lock = new ReentrantReadWriteLock(false);
  14. updateFlag = false;
  15. urlMap = new HashMap<String,String>();
  16. actionMap = new HashMap<String,String>();
  17. urlDao = new UrlDao();
  18. actionDao = new ActionDao();
  19. dbChangeFlag = false;
  20. init();
  21. }
  22. public static UrlAndActionManager getInstence() {
  23. return UrlAndActionManagerHolder.INSTANCE;
  24. }
  25. private void init(){
  26. lock.writeLock().lock();
  27. urlDao.loadUrls(urlMap);
  28. actionDao.loadActions(actionMap);
  29. ARE.getLog().info("urlMap :");
  30. Set set1 = urlMap.keySet();
  31. for (Object object : set1) {
  32. ARE.getLog().info(object + " : " + urlMap.get(object));
  33. }
  34. ARE.getLog().info("actionMap :");
  35. Set set2 = actionMap.keySet();
  36. for (Object object : set2) {
  37. ARE.getLog().info(object + " : " + actionMap.get(object));
  38. }
  39. lock.writeLock().unlock();
  40. this.setName("定期监视资源表更新情况线程");
  41. this.start();
  42. }
  43. //用户权限匹配
  44. public boolean match(String postUrl, UserLoginInfoModel userLogin) {
  45. boolean result = false;
  46. if(null == userLogin) {
  47. return result;
  48. }
  49. String privileges = userLogin.getPrivilegeId();
  50. if(StringX.isEmpty(privileges)) {
  51. privileges = ",,";
  52. }
  53. else {
  54. privileges = "," + privileges + ",";
  55. }
  56. ARE.getLog().debug("postUrl : " + postUrl);
  57. ARE.getLog().debug("userId : " + userLogin.getUserId());
  58. ARE.getLog().debug("privileges : " + privileges);
  59. if(updateFlag) {//当前正在更新map时,从数据库获取权限进行比较
  60. ARE.getLog().debug("从数据库中匹配权限");
  61. String permission = null;
  62. permission = urlDao.findPermissionByUrlId(postUrl);
  63. if(null == permission) {
  64. permission = actionDao.findPermissionByActionId(postUrl);
  65. if((null != permission && privileges.contains(","+permission+",")) || "".equals(permission)) {
  66. result = true;
  67. }
  68. }
  69. else {
  70. if(null != permission && privileges.contains(","+permission+",")) {
  71. result = true;
  72. }
  73. }
  74. }
  75. else {//当前不在更新map时,从map中获取权限进行比较
  76. ARE.getLog().debug("从内存中匹配权限");
  77. lock.readLock().lock();
  78. String url = null;
  79. url = urlMap.get(postUrl);
  80. if(null == url) {//请求为 请求行为资源
  81. String action = null;
  82. action = actionMap.get(postUrl);
  83. if(null == action) {
  84. result = false;
  85. }
  86. else {
  87. if("".equals(action)) {
  88. result = true;
  89. }
  90. else if(privileges.contains(","+action+",")) {
  91. result = true;
  92. }
  93. else {
  94. result = false;
  95. }
  96. }
  97. }
  98. else {//请求为 请求url资源
  99. if("".equals(url)) {
  100. result = true;
  101. }
  102. else if(privileges.contains(","+url+",")) {
  103. result = true;
  104. }
  105. else {
  106. result = false;
  107. }
  108. }
  109. lock.readLock().unlock();
  110. }
  111. return result;
  112. }
  113. @Override
  114. public void run() {
  115. while(true) {
  116. try {
  117. Thread.sleep(1000*60*5);//每隔5分钟执行一次
  118. } catch (InterruptedException e) {
  119. ARE.getLog().debug(e);
  120. }
  121. ARE.getLog().info(this.getName() + " - 开始检测资源权限是否更新");
  122. lock.writeLock().lock();
  123. if(!updateFlag) {
  124. updateFlag = true;
  125. urlDao.loadPermissionUpdateDatas(urlMap);
  126. actionDao.loadPermissionUpdateDatas(actionMap);
  127. updateFlag = false;
  128. }
  129. lock.writeLock().unlock();
  130. ARE.getLog().info(this.getName() + " - 完成检测资源权限是否更新");
  131. }
  132. }
  133. public void dbChange() {
  134. dbChangeFlag = true;
  135. }
  136. }

这个类就是管理类了,它采用了单例模式,在它第一次生成的时候,会去数据库中加载url表和行为表的数据到对应map中,之后便会开启一个线程,通过一个标志位定期检查数据库数据是否更新,若更新则需要对数据库中的数据重新加载,这时线程会对另一个标志位控制,告知想要读取map中数据的程序当前map正在更新,请直接访问数据库,线程完成更新后再置回该标志位.这个类中用到了读写锁,为何不用synchronized呢,这是由于synchronized会对读加锁,由于大多数情况都是读的情况,所以synchronized对效率的影响比较大,而读写锁的读锁之间不互斥,读锁和写锁之间互斥这样能很好的满足我的需求.该管理类对于数据库更新的情况并没有进行锁控制,只使用了标志位,原因是数据库的更新和用户的访问是分开的,用户优先访问内存,而管理类更新map是通过监控线程来控制的,在设计的时候对实时更新的要求不高,所以不需要锁控制(一次检查更新情况时没有更新上,下一次检查时就会更新上).

3.4 ActionDao.java

  1. public class ActionDao {
  2. public List<String> getActionIds() {
  3. Connection conn = null;
  4. PreparedStatement statement = null;
  5. try {
  6. conn = ARE.getDBConnection("craw");
  7. List<String> result = new ArrayList<>();
  8. String sql = "select actionId from security_manage_action";
  9. statement = conn.prepareStatement(sql);
  10. ResultSet resultSet = statement.executeQuery();
  11. if(null != resultSet) {
  12. while(resultSet.next()) {
  13. String actionId = resultSet.getString("actionId");
  14. result.add(actionId);
  15. }
  16. }
  17. resultSet.close();
  18. return result;
  19. } catch(SQLException e) {
  20. ARE.getLog().error(e);
  21. return null;
  22. } finally {
  23. try {
  24. if(null != statement) {
  25. statement.close();
  26. statement = null;
  27. }
  28. if(null != conn) {
  29. conn.close();
  30. conn = null;
  31. }
  32. } catch(SQLException e) {
  33. ARE.getLog().error(e);
  34. }
  35. }
  36. }
  37. public void initAtionRecords(List<String> loads) {
  38. Connection conn = null;
  39. PreparedStatement statement = null;
  40. PreparedStatement statement2 = null;
  41. try {
  42. conn = ARE.getDBConnection("craw");
  43. conn.setAutoCommit(false);
  44. if(null == loads || 0 == loads.size()) {//加载到项目中配置的url数组为空,将数据库中数据删除
  45. String sqlAllDel = "delete from security_manage_action";
  46. statement = conn.prepareStatement(sqlAllDel);
  47. statement.executeQuery();
  48. conn.commit();
  49. return;
  50. }
  51. List<String> olds = getActionIds();
  52. if(null != olds) {
  53. List<String> contains = new ArrayList<>();
  54. for (String string : olds) {
  55. if(loads.contains(string)) {
  56. contains.add(string);
  57. }
  58. }
  59. loads.removeAll(contains); //数据库中没有,项目中存在的路由
  60. olds.removeAll(contains); //数据库中有,项目中不存在的路由
  61. String sqlAdd = "INSERT security_manage_action(actionId,actionName,permission,updateVersion) VALUES(?,'','',1)";
  62. String sqlDel = "DELETE FROM security_manage_action where actionId=?";
  63. if(loads.size() > 0) {
  64. statement = conn.prepareStatement(sqlAdd);
  65. for (String actionId : loads) {
  66. statement.setString(1, actionId);
  67. statement.addBatch();
  68. }
  69. }
  70. if(olds.size() > 0) {
  71. statement2 = conn.prepareStatement(sqlDel);
  72. for (String actionId : olds) {
  73. statement2.setString(1, actionId);
  74. statement2.addBatch();
  75. }
  76. }
  77. if(loads.size() > 0 || olds.size() > 0) {
  78. if(null != statement) {
  79. statement.executeBatch();
  80. }
  81. if(null != statement2) {
  82. statement2.executeBatch();
  83. }
  84. conn.commit();
  85. }
  86. }
  87. } catch(SQLException e) {
  88. try {
  89. conn.rollback();
  90. } catch (SQLException e1) {
  91. ARE.getLog().error(e1);
  92. }
  93. ARE.getLog().error(e);
  94. } finally {
  95. try {
  96. if(null != statement2) {
  97. statement2.close();
  98. statement2 = null;
  99. }
  100. if(null != statement) {
  101. statement.close();
  102. statement = null;
  103. }
  104. if(null != conn) {
  105. conn.setAutoCommit(true);
  106. conn.close();
  107. conn = null;
  108. }
  109. } catch(SQLException e) {
  110. ARE.getLog().error(e);
  111. }
  112. }
  113. }
  114. public boolean loadActions(Map<String,String> actionMap) {
  115. boolean result = true;
  116. Connection conn = null;
  117. PreparedStatement statement = null;
  118. try {
  119. conn = ARE.getDBConnection("craw");
  120. String sql = "select actionId,permission from security_manage_action";
  121. statement = conn.prepareStatement(sql);
  122. ResultSet resultSet = statement.executeQuery();
  123. if(null == resultSet) {
  124. result = false;
  125. }
  126. else {
  127. while(resultSet.next()) {
  128. actionMap.put(resultSet.getString("actionId"),resultSet.getString("permission"));
  129. }
  130. resultSet.close();
  131. }
  132. } catch (SQLException e) {
  133. result = false;
  134. ARE.getLog().error(e);
  135. } finally {
  136. try {
  137. if(null != statement) {
  138. statement.close();
  139. statement = null;
  140. }
  141. if(null != conn) {
  142. conn.close();
  143. conn = null;
  144. }
  145. } catch(SQLException e) {
  146. ARE.getLog().error(e);
  147. }
  148. }
  149. return result;
  150. }
  151. public boolean loadPermissionUpdateDatas(Map<String,String> actionMap) {
  152. boolean result = true;
  153. Connection conn = null;
  154. PreparedStatement statement = null;
  155. PreparedStatement statement2 = null;
  156. try {
  157. conn = ARE.getDBConnection("craw");
  158. conn.setAutoCommit(false);
  159. //查找所有更新permission的数据
  160. String sql = "select actionId,permission,updateVersion from security_manage_action where isUpdate='Y'";
  161. statement = conn.prepareStatement(sql);
  162. ResultSet resultSet = statement.executeQuery();
  163. //将isUpdate置为N
  164. String sql2 = "update security_manage_action set isUpdate='N',updateVersion=updateVersion+1 where actionId=? and updateVersion=? and isUpdate='Y'";
  165. int count = 0;
  166. statement2 = conn.prepareStatement(sql2);
  167. if(null == resultSet) {
  168. result = false;
  169. }
  170. else {
  171. while(resultSet.next()) {
  172. count++;
  173. actionMap.put(resultSet.getString("actionId"),resultSet.getString("permission"));
  174. statement2.setString(1, resultSet.getString("actionId"));
  175. statement2.setInt(2, resultSet.getInt("updateVersion"));
  176. statement2.addBatch();
  177. }
  178. resultSet.close();
  179. }
  180. if(count > 0) {
  181. statement2.executeUpdate();
  182. }
  183. conn.commit();
  184. } catch (SQLException e) {
  185. if(null != conn) {
  186. try {
  187. conn.rollback();
  188. } catch (SQLException e1) {
  189. ARE.getLog().error(e1);;
  190. }
  191. }
  192. result = false;
  193. ARE.getLog().error(e);
  194. } finally {
  195. try {
  196. if(null != statement2) {
  197. statement2.close();
  198. statement2 = null;
  199. }
  200. if(null != statement) {
  201. statement.close();
  202. statement = null;
  203. }
  204. if(null != conn) {
  205. conn.setAutoCommit(true);
  206. conn.close();
  207. conn = null;
  208. }
  209. } catch(SQLException e) {
  210. ARE.getLog().error(e);
  211. }
  212. }
  213. return result;
  214. }
  215. public String findPermissionByActionId(String actionId) {
  216. String result = null;
  217. Connection conn = null;
  218. PreparedStatement statement = null;
  219. try {
  220. conn = ARE.getDBConnection("craw");
  221. String sql = "select permission from security_manage_action where actionId=?";
  222. statement = conn.prepareStatement(sql);
  223. statement.setString(1, actionId);
  224. ResultSet resultSet = statement.executeQuery();
  225. if(null != resultSet) {
  226. resultSet.last();
  227. int count = resultSet.getRow();
  228. if(count > 0) {
  229. result = resultSet.getString("permission");
  230. }
  231. resultSet.close();
  232. }
  233. if(null == result) {
  234. result = "";
  235. }
  236. } catch(SQLException e) {
  237. ARE.getLog().error(e);
  238. } finally {
  239. try {
  240. if(null != statement) {
  241. statement.close();
  242. statement = null;
  243. }
  244. if(null != conn) {
  245. conn.close();
  246. conn = null;
  247. }
  248. } catch(SQLException e) {
  249. ARE.getLog().error(e);
  250. }
  251. }
  252. return result;
  253. }
  254. }

这个是数据库操作类,主要进行数据库数据操作,由于url资源表结构与action表结构一致,数据库操作类功能类似,所以不贴代码了.

3.5 GetAllJspServlet.java

  1. public class GetAllJspServlet extends HttpServlet {
  2. private static final long serialVersionUID = 1L;
  3. public void init(ServletConfig config) throws ServletException {
  4. ARE.getLog().info("GetAllJspServlet start");
  5. ServletContext context = config.getServletContext();
  6. ARE.getLog().info("GetAllJspServlet start");
  7. String[] dirs = {"craw","security","frame/page","parse"};//要扫描的文件目录
  8. List<String> loads = new ArrayList<>();//存储jsp相对路径
  9. for (int i = 0; i < dirs.length; i++) {
  10. File file = new File(context.getRealPath("/") + dirs[i]);
  11. String fatherPath = file.getAbsolutePath();
  12. ARE.getLog().info("dir : " + fatherPath);
  13. File[] files = file.listFiles();
  14. if(null != files && files.length > 0) {
  15. for (int j = 0; j < files.length; j++) {
  16. String filePath = "/" + dirs[i] + files[j].getPath().replace(fatherPath, "");
  17. if(filePath.endsWith(".jsp")) {
  18. ARE.getLog().info(filePath);
  19. loads.add(filePath);
  20. }
  21. }
  22. }
  23. }
  24. new UrlDao().initUrlRecords(loads);
  25. ARE.getLog().info("GetAllJspServlet end");
  26. }
  27. }

这个类是在项目部署启动时,读取指定目录下的所有jsp文件的文件名,与数据库中的url资源对比,进行url资源初始化(以项目读到的jsp为准,修改数据库数据)

3.6 GetAllRequestMappingServlet.java

  1. public class GetAllRequestMappingServlet extends HttpServlet {
  2. private static final long serialVersionUID = 1L;
  3. public void init(ServletConfig config) throws ServletException {
  4. ARE.getLog().info("GetAllRequestMappingServlet start");
  5. // 查找所以springMVC配置的url
  6. ServletContext context = config.getServletContext();
  7. WebApplicationContext webApp = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
  8. RequestMappingHandlerMapping rmhp = webApp.getBean(RequestMappingHandlerMapping.class);
  9. Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
  10. List<String> loads = new ArrayList<>();
  11. for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator.hasNext();) {
  12. RequestMappingInfo info = iterator.next();
  13. String url = info.getPatternsCondition().toString();
  14. if (url.length() >= 2) {
  15. url = url.substring(1, url.length() - 1);
  16. loads.add(url);
  17. ARE.getLog().info(url);
  18. }
  19. }
  20. // 查找web.xml中配置的url
  21. try {
  22. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  23. DocumentBuilder builder = factory.newDocumentBuilder();
  24. File file = new File(context.getRealPath("/")+"WEB-INF/web.xml");
  25. Document doc = (Document) builder.parse(file);
  26. NodeList nodeList = doc.getElementsByTagName("url-pattern");
  27. for (int i = 0; i < nodeList.getLength(); i++) {
  28. Element tyes = (Element)nodeList.item(i);
  29. Text textNode = (Text) tyes.getFirstChild();
  30. String text = textNode.getData().trim();
  31. if(!"null".equals(text) && !text.contains("*")){
  32. ARE.getLog().info(text);
  33. if(!loads.contains(text)) {
  34. loads.add(text);
  35. }
  36. }
  37. }
  38. } catch (Exception e) {
  39. ARE.getLog().error(e);
  40. }
  41. ARE.getLog().info("GetAllRequestMappingServlet init db");
  42. new ActionDao().initAtionRecords(loads);
  43. ARE.getLog().info("GetAllRequestMappingServlet end");
  44. }
  45. }

这个类是在项目启动时,读取所有项目中配置的.do请求(由于项目是使用了springMVC,所以用spring中的类实现这个功能)以及web.xml中配置的请求,作为action资源,并与数据库同步(以读到的数据为准)

4.总结

通过添加url资源表,action表使得整个权限管理系统能够精确到页面级,按钮事件级.而通过管理类把数据加载到内存,减轻了数据库的访问压力,选择使用乐观锁以及开启线程定时检索数据是否更新提高了数据库执行效率.另外,通过项目启动时系统自动检索系统所有资源并与数据库同步,以及杜绝用户新增和删除操作,提高了数据的一致性和安全性.至次0.9版本的用户权限系统升级完毕.
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/825867
推荐阅读
相关标签
  

闽ICP备14008679号