Spring Security3.1 最新配置实例

Spring Security3.1 最新配置实例 (转载) NULL 博文链接:https://grey2.iteye.com/blog/1714086 立即下载

这几天学习了一下Spring Security3.1,从官网下载了Spring Security3.1版本进行练习,经过多次尝试才摸清了其中的一些原理。本人不才,希望能帮助大家。还有,这次我第二次写博客啊,文体不是很行。希望能让观看者不产生疲惫的感觉,我已经心满意足了。

一、数据库结构

     先来看一下数据库结构,采用的是基于角色-资源-用户的权限管理设计。(MySql数据库)

    为了节省篇章,只对比较重要的字段进行注释。

    1.用户表Users

    CREATE TABLE `users` (

       -- 账号是否有限 1. 是 0.否
       `enable` int(11) default NULL,
       `password` varchar(255) default NULL,
       `account` varchar(255) default NULL,
       `id` int(11) NOT NULL auto_increment,
       PRIMARY KEY  (`id`)
    )

 

   2.角色表Roles

   CREATE TABLE `roles` (
     `enable` int(11) default NULL,
     `name` varchar(255) default NULL,
     `id` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`id`)
   )

 

   3 用户_角色表users_roles

   CREATE TABLE `users_roles` (

     --用户表的外键
     `uid` int(11) default NULL,

     --角色表的外键
     `rid` int(11) default NULL,
     `urId` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`urId`),
     KEY `rid` (`rid`),
     KEY `uid` (`uid`),
    CONSTRAINT `users_roles_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`),
    CONSTRAINT `users_roles_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `users` (`id`)
   )

 

   4.资源表resources

   CREATE TABLE `resources` (
     `memo` varchar(255) default NULL,

     -- 权限所对应的url地址
     `url` varchar(255) default NULL,

     --优先权
     `priority` int(11) default NULL,

     --类型
     `type` int(11) default NULL,

     --权限所对应的编码,例201代表发表文章
     `name` varchar(255) default NULL,
     `id` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`id`)
   )

 

   5.角色_资源表roles_resources

    CREATE TABLE `roles_resources` (
      `rsid` int(11) default NULL,
      `rid` int(11) default NULL,
      `rrId` int(11) NOT NULL auto_increment,
      PRIMARY KEY  (`rrId`),
      KEY `rid` (`rid`),
      KEY `roles_resources_ibfk_2` (`rsid`),
      CONSTRAINT `roles_resources_ibfk_2` FOREIGN KEY (`rsid`) REFERENCES `resources` (`id`),
      CONSTRAINT `roles_resources_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`)
      )

 

  二、系统配置

   所需要的jar包,请自行到官网下载,我用的是Spring Security3.1.0.RC1版的。把dist下的除了源码件包导入就行了。还有那些零零碎的   数据库驱动啊,log4j.jar等等,我相信在用Spring Security之前,大家已经会的了。

  1) web.xml

<!-- Spring -->  

  1.   <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>classpath:applicationContext.xml,classpath:applicationContext-security.xml</param-value>  
  4.   </context-param>  
  5.     
  6.       
  7.   <listener>  
  8.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  9.   </listener>  
  10.   <!-- 权限 -->  
  11.   <filter>  
  12.         <filter-name>springSecurityFilterChain</filter-name>  
  13.         <filter-class>  
  14.             org.springframework.web.filter.DelegatingFilterProxy  
  15.         </filter-class>  
  16.    </filter>  
  17.     <filter-mapping>  
  18.         <filter-name>springSecurityFilterChain</filter-name>  
  19.         <url-pattern>/*</url-pattern>  
  20.     </filter-mapping>  

 这里主要是配置了让容器启动的时候加载application-security.xml和Spring Security的权限过滤器代理,让其过滤所有的客服请求。

 2)application-security.xml

<?xml version="1.0" encoding="UTF-8"?>  

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  2.     xmlns:beans="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  5.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  6.                           
  7.     <global-method-security pre-post-annotations="enabled" />   
  8.     <!-- 该路径下的资源不用过滤 -->             
  9.     <http pattern="/js/**" security="none"/>  
  10.     <http use-expressions="true" auto-config="true">  
  11.           
  12.         <form-login />  
  13.         <logout/>  
  14.         <!-- 实现免登陆验证 -->  
  15.         <remember-me />  
  16.         <session-management invalid-session-url="/timeout.jsp">  
  17.             <concurrency-control max-sessions="10" error-if-maximum-exceeded="true" />  
  18.         </session-management>  
  19.         <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>  
  20.     </http>  
  21.     <!-- 配置过滤器 -->  
  22.     <beans:bean id="myFilter" class="com.huaxin.security.MySecurityFilter">  
  23.         <!-- 用户拥有的权限 -->  
  24.         <beans:property name="authenticationManager" ref="myAuthenticationManager" />  
  25.         <!-- 用户是否拥有所请求资源的权限 -->  
  26.         <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />  
  27.         <!-- 资源与权限对应关系 -->  
  28.         <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />  
  29.     </beans:bean>  
  30.     <!-- 实现了UserDetailsService的Bean -->  
  31.     <authentication-manager alias="myAuthenticationManager">  
  32.         <authentication-provider user-service-ref="myUserDetailServiceImpl" />  
  33.     </authentication-manager>  
  34.     <beans:bean id="myAccessDecisionManager" class="com.huaxin.security.MyAccessDecisionManager"></beans:bean>  
  35.     <beans:bean id="mySecurityMetadataSource" class="com.huaxin.security.MySecurityMetadataSource">  
  36.         <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>  
  37.     </beans:bean>  
  38.     <beans:bean id="myUserDetailServiceImpl" class="com.huaxin.security.MyUserDetailServiceImpl">  
  39.         <beans:property name="usersDao" ref="usersDao"></beans:property>  
  40.     </beans:bean>  
  41. </beans:beans>  

 

我们在第二个http标签下配置一个我们自定义的继承了org.springframework.security.access.intercept.AbstractSecurityInterceptor的Filter,并注入其

必须的3个组件authenticationManager、accessDecisionManager和securityMetadataSource。其作用上面已经注释了。

 

<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/> 这里的FILTER_SECURITY_INTERCEPTOR是Spring Security默认的Filter,

我们自定义的Filter必须在它之前,过滤客服请求。接下来看下我们最主要的myFilter吧。

 

3)myFilter

  (1) MySecurityFilter.java 过滤用户请求

 

public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {  
  1.     //与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,  
  2.     //其他的两个组件,已经在AbstractSecurityInterceptor定义  
  3.     private FilterInvocationSecurityMetadataSource securityMetadataSource;  
  4.   
  5.     @Override  
  6.     public SecurityMetadataSource obtainSecurityMetadataSource() {  
  7.         return this.securityMetadataSource;  
  8.     }  
  9.   
  10.     public void doFilter(ServletRequest request, ServletResponse response,  
  11.             FilterChain chain) throws IOException, ServletException {  
  12.         FilterInvocation fi = new FilterInvocation(request, response, chain);  
  13.         invoke(fi);  
  14.     }  
  15.       
  16.     private void invoke(FilterInvocation fi) throws IOException, ServletException {  
  17.         // object为FilterInvocation对象  
  18.                   //super.beforeInvocation(fi);源码  
  19.         //1.获取请求资源的权限  
  20.         //执行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);  
  21.         //2.是否拥有权限  
  22.         //this.accessDecisionManager.decide(authenticated, object, attributes);  
  23.         InterceptorStatusToken token = super.beforeInvocation(fi);  
  24.         try {  
  25.             fi.getChain().doFilter(fi.getRequest(), fi.getResponse());  
  26.         } finally {  
  27.             super.afterInvocation(token, null);  
  28.         }  
  29.     }  
  30.   
  31.     public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {  
  32.         return securityMetadataSource;  
  33.     }  
  34.   
  35.     public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {  
  36.         this.securityMetadataSource = securityMetadataSource;  
  37.     }  
  38.       
  39.     public void init(FilterConfig arg0) throws ServletException {  
  40.         // TODO Auto-generated method stub  
  41.     }  
  42.       
  43.     public void destroy() {  
  44.         // TODO Auto-generated method stub  
  45.           
  46.     }  
  47.   
  48.     @Override  
  49.     public Class<? extends Object> getSecureObjectClass() {  
  50.         //下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误  
  51.         return FilterInvocation.class;  
  52.     }  
  53. }  

  核心的InterceptorStatusToken token = super.beforeInvocation(fi);会调用我们定义的accessDecisionManager:decide(Object object)和securityMetadataSource

  :getAttributes(Object object)方法。

 

 (2)MySecurityMetadataSource.java

 

//1 加载资源与权限的对应关系  

  1. public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {  
  2.     //由spring调用  
  3.     public MySecurityMetadataSource(ResourcesDao resourcesDao) {  
  4.         this.resourcesDao = resourcesDao;  
  5.         loadResourceDefine();  
  6.     }  
  7.   
  8.     private ResourcesDao resourcesDao;  
  9.     private static Map<String, Collection<ConfigAttribute>> resourceMap = null;  
  10.   
  11.     public ResourcesDao getResourcesDao() {  
  12.         return resourcesDao;  
  13.     }  
  14.   
  15.     public void setResourcesDao(ResourcesDao resourcesDao) {  
  16.         this.resourcesDao = resourcesDao;  
  17.     }  
  18.   
  19.     public Collection<ConfigAttribute> getAllConfigAttributes() {  
  20.         // TODO Auto-generated method stub  
  21.         return null;  
  22.     }  
  23.   
  24.     public boolean supports(Class<?> clazz) {  
  25.         // TODO Auto-generated method stub  
  26.         return true;  
  27.     }  
  28.     //加载所有资源与权限的关系  
  29.     private void loadResourceDefine() {  
  30.         if(resourceMap == null) {  
  31.             resourceMap = new HashMap<String, Collection<ConfigAttribute>>();  
  32.             List<Resources> resources = this.resourcesDao.findAll();  
  33.             for (Resources resource : resources) {  
  34.                 Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();  
  35.                                 //以权限名封装为Spring的security Object  
  36.                 ConfigAttribute configAttribute = new SecurityConfig(resource.getName());  
  37.                 configAttributes.add(configAttribute);  
  38.                 resourceMap.put(resource.getUrl(), configAttributes);  
  39.             }  
  40.         }  
  41.           
  42.         Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();  
  43.         Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();  
  44.           
  45.     }  
  46.     //返回所请求资源所需要的权限  
  47.     public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {  
  48.           
  49.         String requestUrl = ((FilterInvocation) object).getRequestUrl();  
  50.         System.out.println("requestUrl is " + requestUrl);  
  51.         if(resourceMap == null) {  
  52.             loadResourceDefine();  
  53.         }  
  54.         return resourceMap.get(requestUrl);  
  55.     }  
  56.   
  57. }  

 这里的resourcesDao,熟悉Dao设计模式和Spring 注入的朋友应该看得明白。

 

(3)MyUserDetailServiceImpl.java

 public class MyUserDetailServiceImpl implements UserDetailsService {  

  1.       
  2.     private UsersDao usersDao;  
  3.     public UsersDao getUsersDao() {  
  4.         return usersDao;  
  5.     }  
  6.   
  7.     public void setUsersDao(UsersDao usersDao) {  
  8.         this.usersDao = usersDao;  
  9.     }  
  10.       
  11.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {  
  12.         System.out.println("username is " + username);  
  13.         Users users = this.usersDao.findByName(username);  
  14.         if(users == null) {  
  15.             throw new UsernameNotFoundException(username);  
  16.         }  
  17.         Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);  
  18.           
  19.         boolean enables = true;  
  20.         boolean accountNonExpired = true;  
  21.         boolean credentialsNonExpired = true;  
  22.         boolean accountNonLocked = true;  
  23.           
  24.         User userdetail = new User(users.getAccount(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);  
  25.         return userdetail;  
  26.     }  
  27.       
  28.     //取得用户的权限  
  29.     private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {  
  30.         Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
  31.         Set<Roles> roles = user.getRoles();  
  32.           
  33.         for(Roles role : roles) {  
  34.             Set<Resources> tempRes = role.getResources();  
  35.             for(Resources res : tempRes) {  
  36.                 authSet.add(new GrantedAuthorityImpl(res.getName()));  
  37. s           }  
  38.         }  
  39.         return authSet;  
  40.     }  
  41. }  

 

(4) MyAccessDecisionManager.java

public class MyAccessDecisionManager implements AccessDecisionManager {  

  1.       
  2.     public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {  
  3.         if(configAttributes == null) {  
  4.             return;  
  5.         }  
  6.         //所请求的资源拥有的权限(一个资源对多个权限)  
  7.         Iterator<ConfigAttribute> iterator = configAttributes.iterator();  
  8.         while(iterator.hasNext()) {  
  9.             ConfigAttribute configAttribute = iterator.next();  
  10.             //访问所请求资源所需要的权限  
  11.             String needPermission = configAttribute.getAttribute();  
  12.             System.out.println("needPermission is " + needPermission);  
  13.             //用户所拥有的权限authentication  
  14.             for(GrantedAuthority ga : authentication.getAuthorities()) {  
  15.                 if(needPermission.equals(ga.getAuthority())) {  
  16.                     return;  
  17.                 }  
  18.             }  
  19.         }  
  20.         //没有权限  
  21.         throw new AccessDeniedException(" 没有权限访问! ");  
  22.     }  
  23.   
  24.     public boolean supports(ConfigAttribute attribute) {  
  25.         // TODO Auto-generated method stub  
  26.         return true;  
  27.     }  
  28.   
  29.     public boolean supports(Class<?> clazz) {  
  30.         // TODO Auto-generated method stub  
  31.         return true;  
  32.     }  
  33.       
  34. }  

 

三、流程

 1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)
 2)用户发出请求
 3)过滤器拦截(MySecurityFilter:doFilter)
 4)取得请求资源所需权限(MySecurityMetadataSource:getAttributes)
 5)匹配用户拥有权限和请求权限(MyAccessDecisionManager:decide),如果用户没有相应的权限,

     执行第6步,否则执行第7步。
 6)登录
 7)验证并授权(MyUserDetailServiceImpl:loadUserByUsername)
 8)重复4,5

 

四、结束语

好了,终于写完了,回头看了一下,感觉不是怎么行。等我弄明白Spring Security它的原理之后,再回头修改下注释吧。大家觉得不妥的地方,可以留言,我会回复大家的。

QT绘制饼图+柱状图+折线图 使用qt绘制,折线图,饼图,柱状图,多柱状图 阅读详情

相关推荐

内网渗透—横向移动&IPC横移&Impacket套件&CS插件

以上便是IPC横移的知识。最后,以上仅为个人的拙见,如何有不对的地方,欢迎各位师傅指正与补充,有兴趣的师傅可以一起交流学习。

2301_76227305的博客 1890

Spring boot 3 (3.1.5) Spring Security 设置一

api/welcome 直接就能看到内容, /api/admin 则返回401。创建两个路由 /api/welcome 和 /api/admin。JWTFilter.java代码见下期,还没整明白。JsonResult代码。

HOOLOO的专栏 959

从零到一:移远EC200UCN_LA OpenCPU开发中的‘避坑’实战指南

本文详细介绍了移远EC200UCN_LA 4G通信模块的OpenCPU开发实战指南,涵盖开发环境搭建、项目构建、通信接口开发、调试技巧及固件升级等关键环节。通过避坑经验和实用技巧,帮助开发者高效完成二次开发,提升4G通信模块的应用开发效率。

weixin_29159711的博客 505

Spring Security 3.1配置与使用

1、使用maven 添加Spring Security的jar 包,在pom.xml中加入: org.springframework.security spring-security-core 3.1.3.RELEASE org.springframework.security spring-security-w

yhhazr的专栏 2万+

【Spreadsheet】香港规范结构设计电子表格库开发方案

深入理解香港本地规范特点和要求结合国际先进标准(Eurocode) 的技术内容考虑香港地理环境特殊性 (台风、地质等)建立完善的质量控制体系保持持续更新维护的能力。

hmywillstronger的博客 1361

Kettle实战:如何用JavaScript脚本实现数据库表批量操作(附完整代码)

本文详细介绍了如何利用Kettle的JavaScript脚本实现数据库表批量操作,包括表名采集、循环遍历和动态SQL生成等关键步骤。通过实战案例和完整代码示例,帮助ETL工程师高效处理数据密集型任务,提升数据库操作的自动化水平。

weixin_29019241的博客 231

【9】Spring Boot 3 集成组件 : 基于spring security的认证权限开发【认证】

:book: 本文核心知识点: - [x] 认证和权限流程 - [x] 认证和权限控制说明 - [x] 认证流程在spring security中的相关理论知识 - [x] JWT认证 - [x] 用户名认证 - [x] session认证 - [x] 认证流程Sepring Security配置

寓教于乐。教己助人 1570

把 ABAP writable CDS view entity 讲透:从只读建模到可写模型的 ABAP CDS 新能力

摘要:SAP引入的writable CDS view entity突破了传统CDS视图只读的限制,允许通过ABAP SQL直接进行数据修改。该特性通过WRITABLE关键字定义,使CDS视图成为与数据库表同等级别的可写对象。其核心价值在于为数据集成、中间层同步等场景提供结构化写入入口,但需注意不应绕过业务规则。最佳实践建议保持底层表结构简单映射,避免复杂变形。这一特性标志着CDS从单纯消费模型向双向数据交互能力的演进,为ABAP开发提供了新的数据边界设计思路。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1313

Spring Security配置

2.LoginSuccessHandler(登录成功处理器)六、创建handler(处理器)与config(配置)层。1.LoginFailHandler(登录失败处理器)1.SecurityApplication(主方法)3.NoLoginHandler(未登录处理器)4.NoAuthHandler(无权限处理器)1.CorsConfig(处理跨域申请)四、配置.xml文件(维护SQL语句)七、配置handler(处理器)层。t_user(用户信息表)t_anth (角色表)八、配置congfig层。

qq_46005551的博客 2680

《嵌入式最全面试题-Offer直通车》目录

嵌入式领域蓬勃发展,嵌入式工程师成为众多科技企业争抢的热门人才。如果你渴望在嵌入式面试中脱颖而出,成功斩获心仪的 offer,那么《嵌入式最全面试题 - Offer直通车》将是你的绝佳选择。本专栏是优快云是热门专栏,100多篇文章,总字数过百万。每月新增订阅用户过百,现在是优惠价9.9元,后面要逐渐恢复原价,早订阅早受益。本专栏精心整理了众多超万字的精华内容,总计达数十万字的嵌入式面试题总结。涵盖从嵌入式基础知识到各大厂面试真题,从驱动开发到操作系统,从硬件到软件等各个方面。

大模型大数据攻城狮的专栏 8400

HBase学习二:RegionServer详解

RegionServer是HBase系统中最核心的组件,主要负责用户数据写入、读取等基础操作。RegionServer组件实际上是一个综合体系,包含多个各司其职的核心模块:HLog、MemStore、HFile以及BlockCache。一个RegionServer由一个(或多个)HLog、一个BlockCache以及多个Region组成。其中,HLog用来保证数据写入的可靠性;BlockCache可以将数据块缓存在内存中以提升数据读取性能;

qwerty1372431588的博客 747

Spring Security3.1 最新配置实例 .

这几天学习了一下Spring Security3.1,从官网下载了Spring Security3.1版本进行练习,经过多次尝试才摸清了其中的一些原理。本人不才,希望能帮助大家。还有,这次我第二次写博客啊,文体不是很行。希望能让观看者不产生疲惫的感觉,我已经心满意足了。 一、数据库结构      先来看一下数据库结构,采用的是基于角色-资源-用户的权限管理设计。(MySql数据库)   

zhangweinet的专栏 706

微信小程序 - [wxapplib]] backgroundfetch privacy fail {“errno”:101,“errMsg”:“private_getBackgroundFetchDa

微信小程序报错之backgroundfetch privacy fail,微信小程序报错WAServiceMainContext.js:1 [wxapplib]] backgroundfetch privacy fail {“errno“:101,怎么解决?问题出现:调用wx.chooseMessageFile报错(开发者工具中正常)用户隐私协议中未声明小程序使用此功能,安卓真机调试报错:backgroundfetch privacy fail ,怎么解决?微信小程序[wxapplib]] backgrou

🏆 前端领域优质创作者 1万+
上一篇: Linux Crontab 定时任务 命令详解
下一篇: Spring Security3
Johnny__Tang
博客等级 码龄18年 9粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值