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的配置文件中的定义一般如下 < ...
随机推荐
- hdu5336 Walk Out
hdu5336 Walk Out 题意是:入口:地图的左上角,出口,地图的右上角,求所经过的路径的二进制数最小 照着题解敲了一遍 思路是:首先 二进制 的 位数 越小 越好,其次 二进制的前缀零越多 ...
- 用lisp来让计算机学会写作
大部分的代码.思路参考了<Ansi Common Lisp>P138~P141. 问题:给一篇英文文本,如何让计算机依据此文本而生成随机但可读的文本.如: |Venture| The Na ...
- java实现文件传输
在windows下装了个linux虚拟机,两者之间传输文件挺麻烦的.写了个简单的文件传输程序,来方便自己数据传送. server 端: import java.io.BufferedReader;im ...
- 调整系统的inode数量
inode节点中,记录了文件的类型.大小.权限.所有者.文件连接的数目.创建时间与更新时间等重要的信息,还有一个比较重要的内容就是指向数据块的指针. 一般情况不需要特殊配置,如果存放文件很多,需要配置 ...
- Python源码学习十一 一个常用的内存分配函数
void * _PyObject_DebugMallocApi(char id, size_t nbytes) { uchar *p; /* base address of malloc'ed blo ...
- mfc修改应用程序外观
1.在窗口创建前修改窗体外观 在BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)函数中修改,其中CREATESTRUCT结构中有诸如窗口大小 ...
- 浏览器打开URL的方式和加载过程
不同浏览器的工作方式不完全一样,大体上,浏览器的核心是浏览器引擎,目前市场占有率最高的几种浏览器几乎都使用了不同的浏览器引擎:IE使用的是Trident.Firefox使用的是Gecko.Safari ...
- UVALive 2519 Radar Installation 雷达扫描 区间选点问题
题意:在坐标轴中给出n个岛屿的坐标,以及雷达的扫描距离,要求在y=0线上放尽量少的雷达能够覆盖全部岛屿. 很明显的区间选点问题. 代码: /* * Author: illuz <iilluzen ...
- 浅谈MySQL 数据库性能优化
MySQL数据库是 IO 密集型的程序,和其他数据库一样,主要功能就是数据的持久化以及数据的管理工作.本文侧重通过优化MySQL 数据库缓存参数如查询缓存,表缓存,日志缓存,索引缓存,innodb缓存 ...
- 管道是如何处理HTTP请求的?
管道是如何处理HTTP请求的? 我们知道ASP.NET Core请求处理管道由一个服务器和一组有序的中间件组成,所以从总体设计来讲是非常简单的,但是就具体的实现来说,由于其中涉及很多对象的交互,我想很 ...