zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    HTML CSS 特殊字符表
    vscode代码统计——Vscode counter
    js数组方法整理
    CSS-界面滚动时不显示滚动条
    Vue Loader 作用域CSS(scoped)——/deep/ 深入组件选择器
    PHP模板引擎,Smarty定义
    mysql触发器trigger 实例详解
    mysql关于数据库表的水平拆分和垂直拆分
    关于数据库表的水平拆分和垂直拆分
    使用Merge存储引擎实现MySQL分表
  • 原文地址:https://www.cnblogs.com/softidea/p/4324698.html
Copyright © 2011-2022 走看看