最近公司要做开发平台,对安全要求比较高;SPRING SECURTIY框架刚好对所有安全问题都有涉及,框架的作者最近还做了spring-session项目实现分布式会话管理,还有他的另一个开源项目spring-security-oauth2。           关于spring-security的配置方法,网上有非常多的介绍,大都是基于XML配置,配置项目非常多,阅读和扩展都不方便。其实spring-security也有基于java的配置方式,今天就讲讲如何通过java配置方式,扩展spring-security实现权限配置全部从表中读取。 
    直接上代码: 
application.properties配置文件

  1. privilesByUsernameQuery= select  authority from user_authorities  where username = ?
  2. allUrlAuthoritiesQuery=SELECT authority_id , url   FROM Url_Authorities

javaconfig

  1. /**
  2. *
  3. */
  4. package com.sivalabs.springapp.config;
  5. import java.util.List;
  6. import javax.annotation.Resource;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.core.env.Environment;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  13. //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  14. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  15. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  16. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  17. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  18. import org.springframework.util.StringUtils;
  19. import com.sivalabs.springapp.entities.UrlAuthority;
  20. import com.sivalabs.springapp.repositories.UserRepository;
  21. /**
  22. * @author tony
  23. *
  24. */
  25. @Configuration
  26. @EnableWebSecurity(debug = true)
  27. // @EnableGlobalMethodSecurity(prePostEnabled = true)
  28. // @ImportResource("classpath:applicationContext-security.xml")
  29. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  30. @Autowired
  31. JdbcTemplate jdbcTemplate ;
  32. @Autowired
  33. private Environment env;
  34. @Bean
  35. CustomUserDetailsService customUserDetailsService() {
  36. //==================application.properties文件中配置2个SQL=============
  37. //privilesByUsernameQuery= select  authority from user_authorities  where username = ?
  38. //allUrlAuthoritiesQuery=SELECT authority_id , url   FROM Url_Authorities
  39. String privilesByUsernameQuery = env.getProperty("privilesByUsernameQuery");
  40. String allUrlAuthoritiesQuery = env.getProperty("allUrlAuthoritiesQuery");
  41. CustomUserDetailsService customUserDetailsService = new CustomUserDetailsService();
  42. customUserDetailsService.setJdbcTemplate(jdbcTemplate);
  43. customUserDetailsService.setEnableGroups(false);
  44. //根据登录ID,查登录用户的所有权限
  45. if(StringUtils.hasLength(privilesByUsernameQuery))
  46. customUserDetailsService.setAuthoritiesByUsernameQuery(privilesByUsernameQuery);
  47. //所有URL与权限的对应关系
  48. if(StringUtils.hasLength(privilesByUsernameQuery))
  49. customUserDetailsService.setAllUrlAuthoritiesQuery(allUrlAuthoritiesQuery);
  50. return customUserDetailsService;
  51. }
  52. @Resource(name = "userRepository")
  53. private UserRepository userRepository;
  54. @Override
  55. protected void configure(AuthenticationManagerBuilder registry)
  56. throws Exception {
  57. /*
  58. * registry .inMemoryAuthentication() .withUser("siva") // #1
  59. * .password("siva") .roles("USER") .and() .withUser("admin") // #2
  60. * .password("admin") .roles("ADMIN","USER");
  61. */
  62. // registry.jdbcAuthentication().dataSource(dataSource);
  63. registry.userDetailsService(customUserDetailsService());
  64. }
  65. @Override
  66. public void configure(WebSecurity web) throws Exception {
  67. web.ignoring().antMatchers("/resources/**"); // #3web
  68. }
  69. // AntPathRequestMatcher --> AntPathRequestMatcher --->AntPathMatcher
  70. @Override
  71. protected void configure(HttpSecurity http) throws Exception {
  72. //1.登录注册等URL不要身份验证
  73. http.csrf().disable().authorizeRequests()
  74. .antMatchers("/login", "/login/form**", "/register", "/logout")
  75. .permitAll() // #4
  76. .antMatchers("/admin", "/admin/**").hasRole("ADMIN"); // #6
  77. //2. 从数据库中读取所有需要权限控制的URL资源,注意当新增URL控制时,需要重启服务
  78. List<UrlAuthority> urlAuthorities = customUserDetailsService().loadUrlAuthorities();
  79. for (UrlAuthority urlAuthority : urlAuthorities) {
  80. http.authorizeRequests().antMatchers(urlAuthority.getUrl()).hasAuthority(String.valueOf(urlAuthority.getId()));
  81. }
  82. //3. 除1,2两个步骤验证之外的URL资源,只要身份认证即可访问
  83. http.authorizeRequests().anyRequest().authenticated() // 7
  84. .and().formLogin() // #8
  85. .loginPage("/login/form") // #9
  86. .loginProcessingUrl("/login").defaultSuccessUrl("/welcome") // #defaultSuccessUrl
  87. .failureUrl("/login/form?error").permitAll(); // #5
  88. }
  89. }

1.读取数据库中的URL资源对应的权限列表  2.读取登录用户拥有的权限列表

  1. /**
  2. *
  3. */
  4. package com.sivalabs.springapp.config;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.List;
  8. import org.springframework.jdbc.core.RowMapper;
  9. import org.springframework.security.core.GrantedAuthority;
  10. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  11. import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
  12. import com.sivalabs.springapp.entities.UrlAuthority;
  13. /**
  14. * @author tony
  15. *
  16. */
  17. public class CustomUserDetailsService extends JdbcDaoImpl{
  18. private String allUrlAuthoritiesQuery ;
  19. /**
  20. * 从数据库中读取所有需要权限控制的URL资源,注意当新增URL控制时,需要重启服务
  21. */
  22. public List<UrlAuthority> loadUrlAuthorities( ) {
  23. return getJdbcTemplate().query(allUrlAuthoritiesQuery,  new RowMapper<UrlAuthority>() {
  24. public UrlAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
  25. return new UrlAuthority (rs.getInt(1),rs.getString(2));
  26. }
  27. });
  28. }
  29. /**
  30. *  从数据库中读取用户权限
  31. * Loads authorities by executing the SQL from <tt>authoritiesByUsernameQuery</tt>.
  32. * @return a list of GrantedAuthority objects for the user
  33. */
  34. protected List<GrantedAuthority> loadUserAuthorities(String username) {
  35. return getJdbcTemplate().query(super.getAuthoritiesByUsernameQuery(), new String[] {username}, new RowMapper<GrantedAuthority>() {
  36. public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
  37. String roleName =  rs.getString(1);
  38. return new SimpleGrantedAuthority(roleName);
  39. }
  40. });
  41. }
  42. public void setAllUrlAuthoritiesQuery(String allUrlAuthoritiesQuery) {
  43. this.allUrlAuthoritiesQuery = allUrlAuthoritiesQuery;
  44. }
  45. }

测试数据及案例见  http://note.youdao.com/share/?id=c20e348d9a08504cd3ac1c7c58d1026e&type=note 
spring-security-oauth2  http://www.mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 
Maven Repository: org.springframework.session » spring-session  http://www.mvnrepository.com/artifact/org.springframework.session/spring-session

http://json20080301.iteye.com/blog/2190711

spring-security3.2.5实现中国式安全管理(转)的更多相关文章

  1. Spring Security3学习实例

    Spring Security是什么? Spring Security,这是一种基于Spring AOP和Servlet过滤器的安全框架.它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理 ...

  2. Spring security3

    最近一直在学习spring security3,试着搭建了环境: 构建maven环境 项目配置pom.xml文件 <project xmlns="http://maven.apache ...

  3. Spring Security3实现,权限动态获取

    Spring Security3实现,权限动态获取 原文  http://blog.csdn.net/yangwei19680827/article/details/9359113 主题 网络安全Sp ...

  4. Spring Security3详细配置

    Spring Security3详细配置 表名:RESOURCE 解释:资源表备注: 资源表 RESOURCE(资源表) 是否主键 字段名 字段描述 数据类型 长度 可空 约束 缺省值 备注 是 ID ...

  5. Spring Security3 - MVC 整合教程

    下面我们将实现关于Spring Security3的一系列教程.  最终的目标是整合Spring Security + Spring3MVC  完成类似于SpringSide3中mini-web的功能 ...

  6. JavaEE学习之Spring Security3.x——模拟数据库实现用户,权限,资源的管理

    一.引言 因项目需要最近研究了下Spring Security3.x,并模拟数据库实现用户,权限,资源的管理. 二.准备 1.了解一些Spring MVC相关知识: 2.了解一些AOP相关知识: 3. ...

  7. Spring Security3十五日研究(转载)

    前言 南朝<述异记>中记载,晋王质上山砍柴,见二童子下棋,未看完,斧柄已烂,下山回村,闻同代人都去世了,自已还未变老.    因此发出“山中方一日,世上几千年” 的慨叹.原文寥寥几笔,读来 ...

  8. spring security3.1配置比较纠结的2个问题

    转自:http://www.iteye.com/topic/1122629 总论无疑问的,spring security在怎么保护网页应用安全上做得很强很周全,但有些地方还是很差强人意,比如对< ...

  9. 使用Spring Security3的四种方法概述

    使用Spring Security3的四种方法概述 那么在Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户.权限.资源(url)硬编码在xml文件中,已经实现过, ...

  10. Spring Security3中的-authentication-manager标签详解

    讲解完http标签的解析过程,authentication-manager标签解析部分就很容易理解了 authentication-manager标签在spring的配置文件中的定义一般如下 < ...

随机推荐

  1. State Design Pattern 状态设计模式

    设置好内部状态,然后依据不同的函数作为行为模式,进行状态转换. 有点像Finite Automata算法,两者的思想是一样的. 会Finite Automata,那么这个设计模式就非常easy了. # ...

  2. 【视频】零基础学Android开发:蓝牙聊天室APP(四)

    零基础学Android开发:蓝牙聊天室APP第四讲 4.1 ListView控件的使用 4.2 BaseAdapter具体解释 4.3 ListView分布与滚动事件 4.4 ListView事件监听 ...

  3. 微软Ajax--UpdatePanel控件

    今天用做日历显示本月的考勤记录,用到了UpdatePanel控件,才发现对这个控件并不太了解,所以找了点儿资料,整理了一下给大家发上来! 一.UpdatePanel的结构 <asp:Script ...

  4. Eclipse更改默认工作目录的方法

    参考: Eclipse更改默认工作目录的方法:http://blog.163.com/take_make/blog/static/208212210201272611406227/ 用记事本打开&qu ...

  5. 引用iscroll的一个封装方法

    var Page = function(cid, data,callback) { var _self = this; var cid = $(cid); var currPage=1; // 下拉上 ...

  6. 【Java线程】volatile的适用场景

    http://www.ibm.com/developerworks/cn/java/j-jtp06197.html 把代码块声明为 synchronized,有两个重要后果,通常是指该代码具有 原子性 ...

  7. KMP原理、分析及C语言实现

    (是在matrix67博客基础上整理而来,整理着:华科小涛@http://www.cnblogs.com/hust-ghtao/) 有些算法可以让人发疯,KMP算法就是一个.在网上找了很多资料讲的都让 ...

  8. gaoyong的干货

    http://blog.163.com/you888@188/blog/static/6723961920169319529515/    1.xe6安卓编程入门教程,一本很好的资料,全是干货,书印刷 ...

  9. [置顶] Objective-C ,ios,iphone开发基础:ios数据库(The SQLite Database),使用终端进行简单的数据库操作

    SQLite  是一个轻量级的免费关系数据库.SQLite最初的设计目标是用于嵌入式系统,它占用资源非常少,在嵌入式设备中,只需要几百K的内存就够了,可以在(http://www.sqlite.org ...

  10. ExtJs4 笔记(13) Ext.menu.Menu 菜单、Ext.draw.Component 绘图、Ext.resizer.Resizer 大小变更

    本篇讲解菜单.绘图.还有大小变更控件.菜单控件可以附加到各种其他控件中,比如按钮.工具栏等,甚至可以直接通过通过右键打开(模拟右键菜单):ext对绘图的支持可以让我们通过js来绘图:大小变更控件可以让 ...