spring-security3.2.5实现中国式安全管理(转)
直接上代码:
application.properties配置文件
- privilesByUsernameQuery= select authority from user_authorities where username = ?
- allUrlAuthoritiesQuery=SELECT authority_id , url FROM Url_Authorities
javaconfig
- /**
- *
- */
- package com.sivalabs.springapp.config;
- import java.util.List;
- import javax.annotation.Resource;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.env.Environment;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
- //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.builders.WebSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.util.StringUtils;
- import com.sivalabs.springapp.entities.UrlAuthority;
- import com.sivalabs.springapp.repositories.UserRepository;
- /**
- * @author tony
- *
- */
- @Configuration
- @EnableWebSecurity(debug = true)
- // @EnableGlobalMethodSecurity(prePostEnabled = true)
- // @ImportResource("classpath:applicationContext-security.xml")
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- JdbcTemplate jdbcTemplate ;
- @Autowired
- private Environment env;
- @Bean
- CustomUserDetailsService customUserDetailsService() {
- //==================application.properties文件中配置2个SQL=============
- //privilesByUsernameQuery= select authority from user_authorities where username = ?
- //allUrlAuthoritiesQuery=SELECT authority_id , url FROM Url_Authorities
- String privilesByUsernameQuery = env.getProperty("privilesByUsernameQuery");
- String allUrlAuthoritiesQuery = env.getProperty("allUrlAuthoritiesQuery");
- CustomUserDetailsService customUserDetailsService = new CustomUserDetailsService();
- customUserDetailsService.setJdbcTemplate(jdbcTemplate);
- customUserDetailsService.setEnableGroups(false);
- //根据登录ID,查登录用户的所有权限
- if(StringUtils.hasLength(privilesByUsernameQuery))
- customUserDetailsService.setAuthoritiesByUsernameQuery(privilesByUsernameQuery);
- //所有URL与权限的对应关系
- if(StringUtils.hasLength(privilesByUsernameQuery))
- customUserDetailsService.setAllUrlAuthoritiesQuery(allUrlAuthoritiesQuery);
- return customUserDetailsService;
- }
- @Resource(name = "userRepository")
- private UserRepository userRepository;
- @Override
- protected void configure(AuthenticationManagerBuilder registry)
- throws Exception {
- /*
- * registry .inMemoryAuthentication() .withUser("siva") // #1
- * .password("siva") .roles("USER") .and() .withUser("admin") // #2
- * .password("admin") .roles("ADMIN","USER");
- */
- // registry.jdbcAuthentication().dataSource(dataSource);
- registry.userDetailsService(customUserDetailsService());
- }
- @Override
- public void configure(WebSecurity web) throws Exception {
- web.ignoring().antMatchers("/resources/**"); // #3web
- }
- // AntPathRequestMatcher --> AntPathRequestMatcher --->AntPathMatcher
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- //1.登录注册等URL不要身份验证
- http.csrf().disable().authorizeRequests()
- .antMatchers("/login", "/login/form**", "/register", "/logout")
- .permitAll() // #4
- .antMatchers("/admin", "/admin/**").hasRole("ADMIN"); // #6
- //2. 从数据库中读取所有需要权限控制的URL资源,注意当新增URL控制时,需要重启服务
- List<UrlAuthority> urlAuthorities = customUserDetailsService().loadUrlAuthorities();
- for (UrlAuthority urlAuthority : urlAuthorities) {
- http.authorizeRequests().antMatchers(urlAuthority.getUrl()).hasAuthority(String.valueOf(urlAuthority.getId()));
- }
- //3. 除1,2两个步骤验证之外的URL资源,只要身份认证即可访问
- http.authorizeRequests().anyRequest().authenticated() // 7
- .and().formLogin() // #8
- .loginPage("/login/form") // #9
- .loginProcessingUrl("/login").defaultSuccessUrl("/welcome") // #defaultSuccessUrl
- .failureUrl("/login/form?error").permitAll(); // #5
- }
- }
1.读取数据库中的URL资源对应的权限列表 2.读取登录用户拥有的权限列表
- /**
- *
- */
- package com.sivalabs.springapp.config;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
- import com.sivalabs.springapp.entities.UrlAuthority;
- /**
- * @author tony
- *
- */
- public class CustomUserDetailsService extends JdbcDaoImpl{
- private String allUrlAuthoritiesQuery ;
- /**
- * 从数据库中读取所有需要权限控制的URL资源,注意当新增URL控制时,需要重启服务
- */
- public List<UrlAuthority> loadUrlAuthorities( ) {
- return getJdbcTemplate().query(allUrlAuthoritiesQuery, new RowMapper<UrlAuthority>() {
- public UrlAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
- return new UrlAuthority (rs.getInt(1),rs.getString(2));
- }
- });
- }
- /**
- * 从数据库中读取用户权限
- * Loads authorities by executing the SQL from <tt>authoritiesByUsernameQuery</tt>.
- * @return a list of GrantedAuthority objects for the user
- */
- protected List<GrantedAuthority> loadUserAuthorities(String username) {
- return getJdbcTemplate().query(super.getAuthoritiesByUsernameQuery(), new String[] {username}, new RowMapper<GrantedAuthority>() {
- public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
- String roleName = rs.getString(1);
- return new SimpleGrantedAuthority(roleName);
- }
- });
- }
- public void setAllUrlAuthoritiesQuery(String allUrlAuthoritiesQuery) {
- this.allUrlAuthoritiesQuery = allUrlAuthoritiesQuery;
- }
- }
测试数据及案例见 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
- springmvc-datajpa-security-demo.zip (964.9 KB)
http://json20080301.iteye.com/blog/2190711
spring-security3.2.5实现中国式安全管理(转)的更多相关文章
- Spring Security3学习实例
Spring Security是什么? Spring Security,这是一种基于Spring AOP和Servlet过滤器的安全框架.它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理 ...
- Spring security3
最近一直在学习spring security3,试着搭建了环境: 构建maven环境 项目配置pom.xml文件 <project xmlns="http://maven.apache ...
- Spring Security3实现,权限动态获取
Spring Security3实现,权限动态获取 原文 http://blog.csdn.net/yangwei19680827/article/details/9359113 主题 网络安全Sp ...
- Spring Security3详细配置
Spring Security3详细配置 表名:RESOURCE 解释:资源表备注: 资源表 RESOURCE(资源表) 是否主键 字段名 字段描述 数据类型 长度 可空 约束 缺省值 备注 是 ID ...
- Spring Security3 - MVC 整合教程
下面我们将实现关于Spring Security3的一系列教程. 最终的目标是整合Spring Security + Spring3MVC 完成类似于SpringSide3中mini-web的功能 ...
- JavaEE学习之Spring Security3.x——模拟数据库实现用户,权限,资源的管理
一.引言 因项目需要最近研究了下Spring Security3.x,并模拟数据库实现用户,权限,资源的管理. 二.准备 1.了解一些Spring MVC相关知识: 2.了解一些AOP相关知识: 3. ...
- Spring Security3十五日研究(转载)
前言 南朝<述异记>中记载,晋王质上山砍柴,见二童子下棋,未看完,斧柄已烂,下山回村,闻同代人都去世了,自已还未变老. 因此发出“山中方一日,世上几千年” 的慨叹.原文寥寥几笔,读来 ...
- spring security3.1配置比较纠结的2个问题
转自:http://www.iteye.com/topic/1122629 总论无疑问的,spring security在怎么保护网页应用安全上做得很强很周全,但有些地方还是很差强人意,比如对< ...
- 使用Spring Security3的四种方法概述
使用Spring Security3的四种方法概述 那么在Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户.权限.资源(url)硬编码在xml文件中,已经实现过, ...
- Spring Security3中的-authentication-manager标签详解
讲解完http标签的解析过程,authentication-manager标签解析部分就很容易理解了 authentication-manager标签在spring的配置文件中的定义一般如下 < ...
随机推荐
- 基于visual Studio2013解决C语言竞赛题之1045打印成绩
题目 解决代码及点评 /* 功能:用记录来描述一个学生的成绩情况,内容包括:姓名.学号.数学成绩和PASCAL成绩. 要求对一个小组的10个学生的成绩进行统计处理: 1)计算学生的总 ...
- Android开发之大位图二次採样压缩处理(源码分享)
图片有各种形状和大小.在很多情况下这些图片是远远大于我们的用户界面(UI)且占领着极大的内存空间,假设我们不正确位图进行压缩处理,我们的程序会发生内存泄露的错误. MainActivity的代码 pa ...
- oracle 的常用语句
第一部分 基本语法 //拼接表字段 select id || 'is' || name from admin select * from emp where ename like '% ...
- perl 登陆电信猫
登陆电信猫: use LWP::UserAgent; use HTTP::Date qw(time2iso str2time time2iso time2isoz); use Net::Ping; u ...
- javascript 变量转义
$(this).append('<a href="2-1partner.html"><div><img width="645" h ...
- JavaScript编程:浏览器对象模型BOM
4.浏览器对象模型BOM: document.body.offsetwidth可以获取浏览器宽度. Window对象: 窗口操作: 1.moveBy(dx,dy ...
- ORA-00942:表或视图不存在(低级错误)
在好多时候.调试PL/SQL对象时会报.ORA-00942 看看错误原因吧: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamFjc29uX2JhaQ== ...
- GNOME界面简单使用
GNOME界面 CentOS下的文件夹打开方式,默认是打开一个文件夹就重新的打开一个窗口,并不是在原有的文件夹中显示要打开文件夹的内容. 怎么修改: 打开任意一个文件夹. Edit --> pr ...
- delphi不同版本字符串类型的演化(要支持基于firemonkey的app调用,字符串最好使用olevariant类型)
string,DELPHI2009以前的版本string=ansistring,一个字符占一个字节,DELPHI2009及以上版本string=unicodestring,一个字符占二个字节. cha ...
- javascript创建类的6种方式
javascript创建类的7种方式 一 使用字面量创建 1.1 示例 var obj={}; 1.2 使用场景 比较适用于临时构建一个对象,且不关注该对象的类型,只用于临时封装一次数据,且不适合代码 ...