spring-security3.2.5实现中国式安全管理(转)

 

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

Java代码 

 

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

javaconfig 

Java代码 

 

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

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

Java代码 

 

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

测试数据及案例见  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

时间: 2024-09-17 04:13:25

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

关于spring security3中密码获取的问题

问题描述 我在配置spring security3中,有一个非常困惑的问题. 在登录页面,基于 /j_spring_security_check 的登录后,继承UserDetailsService接口,并且实现函数loadByUserName(String username). 我要问的是,我如何取得密码?传递进来的只是一个帐户,没有密码. 还是我对登录这块理解错误?望指教. 问题补充:yangzhanchun 写道 解决方案 load到了User对象后,框架会帮你匹配密码是否正确解决方案二:S

spring security3拦截器问题

问题描述 spring security3拦截器问题 未登录系统的情况下,第一次访问页面会跳转到登录页面,第二次访问就能够访问 配置如下: <http entry-point-ref="loginAuthenticationEntryPoint" > <!-- UsernamePasswordAuthenticationFilter default-target-url 指定了从登录页面登录后进行跳转的页面 always-use-default-target true

security-请教spring Security3 http 与 https互转

问题描述 请教spring Security3 http 与 https互转 不使用http标签配置,使用ChannelProcessingFilter方式,请高手指点 解决方案 http://dead-knight.iteye.com/blog/1521223 解决方案二: 这个帖子我看 了 能否给出xml配置的配置信息

Spring3.2和Spring Security3.1共存的问题?

问题描述 有一个新开始的项目,想用spring3.2和spring security3.1.4,但是再maven中指定了各个spring组件的版本后,spring-core-3.1.4的版本也被包含进来了.请问有没有解决办法?难道用了spring security3.1.4后就只能用spring3.1.4了吗? 解决方案 exclude 排除如 <dependency> <groupId>commons-beanutils</groupId> <artifactI

spring security3 用户的权限信息,角色及资源信息放入缓存里面?

问题描述 spring security3 用户的权限信息,角色及资源信息放入缓存里面? 修改或删除时更新缓存信息? 解决方案 spring security3 不关注你的用户,角色,权限等信息从哪来,只关心有没有这些数据放置缓存是你自己需要配置的,然后spring security3 在通过你配置的这些信息取得所要的数据 ,放不放缓存,spring security3都可以工作.只是放在缓存里是为了提高程序的执行效率,对于修改,添加,删除用户,角色等,肯定要更新缓存的解决方案二:这样也可以啊.

spring security3.24后applicationContext-security.xml中schema配置出错解决方法

   我在以前的一个老项目中使用的spring security的版本是spring-core-3.0.1.RELEASE.jar,其他的相关依赖的包也是这个版本的,但在我在新的项目中把包的版本升级成了3.24的:使用的配置文件还是用原来3.01的applicationContext-security.xml-old. <spring.version>3.2.4.RELEASE</spring.version> <spring.security.version>3.2.

spring security3 登录的时候为什么会触发sessionDestroyed

问题描述 项目用springsecurity3做的登录为了做在线用户又自定义了一个监听器,packagecom.servlet;importjava.text.SimpleDateFormat;importjava.util.*;importjavax.servlet.*;importjavax.servlet.http.*;importorg.springframework.web.context.support.WebApplicationContextUtils;importorg.spr

Spring Security3 有关权限的问题

问题描述 我先前开发中,对于权限问题,都是这样做的:首先建立4张表,用户表,角色表,权限表,资源表然后利用spring中的拦截器对所访问的资源进行拦截,判断这个资源是不是属于该用户权限的一部分.从而决定,是不是允许其访问.我想问下,如果,我现在用springsecurity中的权限管理,请问应该怎么做哦?希望能给我一个实例哦,谢谢 解决方案 解决方案二:晕,居然没人关注解决方案三:大家在权限这一块,都没有用springsecurity3吗?解决方案四:我有用过,但不是很熟悉加我QQ吧353263

spring security3 session过期,拦截异步请求返回登陆页面

问题描述 项目安全用的是springsecurity3.1.2框架,同步跳转时,Session过期,拦截回登陆页面没问题,但遇到AJax或是jQuery,easyui等,异步请求时,springsecurity3拦截了请求,但确无法跳转到登陆页面,有法办解决吗?详细一下.我在线等 解决方案 解决方案二:统一封装AJAX请求吧,监听响应头,如果sessionStatus是timeout那就用JS跳到登录就好了window.location解决方案三:能详细点吗?解决方案四:做一个空白的页面例如ti