当前位置: 首页 > news >正文

springSecurity学习之springSecurity过滤web请求

过滤web请求

在spring中存在一个DelegatingFilterProxy,是一种特殊的Filter,主要任务就是将工作委托给Filter实现类

使用@EnableWebSecurity注解时引入FilterChainProxy

@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();
}

可以使用WebApplicationInitializer的方式来配置DelegatingFilterProxy,其会自动为每个url注册springSecurityFilterChain过滤器(也就是DelegatingFilterProxy),添加一个ContextLoaderListener来载入WebSecurityConfig

// AbstractSecurityWebApplicationInitializer类实现了WebApplicationInitializer接口,spring会发现,并在web容器中注册DelegatingFilterProxy
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {}

DelegatingFilterProxy会拦截发往应用中的请求,并将请求委托给springSecurityFilterChain,springSecurityFilterChain本身是另一种特殊的Filter,可以连接任意一个或多个其他的Filter

private void insertSpringSecurityFilterChain(ServletContext servletContext) {// DEFAULT_FILTER_NAME就是springSecurityFilterChainString filterName = DEFAULT_FILTER_NAME;DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy(filterName);String contextAttribute = getWebApplicationContextAttribute();if (contextAttribute != null) {springSecurityFilterChain.setContextAttribute(contextAttribute);}registerFilter(servletContext, true, filterName, springSecurityFilterChain);
}

配置Spring Security

使用@EnableWebSecurity注解来启用web安全功能,需要配置在实现了WebSecurityConfigurer或者继承WebSecurityConfigurerAdapter类的bean上

@Configuration
@EnableWebSecurity // 引入了WebSecurityConfiguration和AuthenticationConfiguration配置
// 继承WebSecurityConfigurerAdapter来自定义配置,只会覆盖修改的配置,不会覆盖不相关的配置
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {// 通过重载,配置userDetail服务,认证相关的配置protected void configure(AuthenticationManagerBuilder auth) throws Exception {}// 通过重载,配置Filter链public void configure(WebSecurity web) throws Exception {}// 通过重载,配置如何通过拦截器保护请求protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();}
}
用户信息获取

首先来将第一个configure方法,来进行用户信息的获取

// 通过重载,配置userDetail服务protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService);}

使用自定义的用户服务

public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate AdminDao adminDao;@Transactional(readOnly = true)public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {// 查找用户Admin user = adminDao.findByName(username);if (user == null) {throw new UsernameNotFoundException("Username not found");}// 创建权限List<GrantedAuthority> authorities = new ArrayList<>();authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));return new org.springframework.security.core.userdetails.User(user.getUser_name(), user.getPassword(),authorities);}
}
详细样例
 // 通过重载,配置如何通过拦截器保护请求protected void configure(HttpSecurity http) throws Exception {// 对不同的请求进行不同程度的认证http.formLogin() // 配置登录页.loginPage("/login.html")  // 自定义编写登录页面.loginProcessingUrl("/user/login") // 登录访问路径.defaultSuccessUrl("/index") // 登陆成功之后跳转路径.and().logout().logoutUrl("/logout") // 退出登录的路径.logoutSuccessUrl("/index") // 退出登录成功的页面.and().authorizeRequests() // // 配置请求级别的认证.antMatchers("/","/test/").permitAll() // permitAll表示可以直接访问,不需要认证.antMatchers("/user").authenticated() //authenticated表示必须已经登录了系统 .antMatchers("/admin/").hasAuthority("admin") // hasAuthority用户具备该权限可以访问.antMatchers("/teacher/").hasAnyAuthority("admin","teacher")  // hasAnyAuthority用户具备其中一个权限就可以访问.antMatchers("/super/").hasRole("admin")  //hasRole用户具备该角色可以访问,会拼接一个ROLE_前缀,使用的是角色是 ROLE_admin.antMatchers("/student/").hasAnyRole("admin","teacher","student") // hasAnyRole如果用户具备其中一个角色就可以访问.antMatchers("/school/").access("hasRole('admin')") //access使用给定的spel表达式来计算结果 .antMatchers("/ss/").anonymous()  // anonymous允许匿名用户访问.antMatchers("/supper/").denyAll() // denyAll拒绝所有访问.antMatchers("/full/").fullyAuthenticated() //fullyAuthenticated 用户需要是完整认证(不是通过remeber-me功能认证的)允许访问.antMatchers("/ip/").hasIpAddress("127.0.0.1") // hasIpAddress 请求来自指定ip可以访问.antMatchers("/reme/").rememberMe() // 用户通过remember-me功能认证的允许访问.anyRequest().authenticated() // 其他需要认证.and().requiresChannel().anyRequest().requiresSecure() //requiresSecure配置需要https来进行访问  requiresInsecure配置需要http来进行访问.and().rememberMe().tokenValiditySeconds(3600).key("zhang") // rememberMe功能,保存时间3600s,rememberMe是将token存储在cookie中的,token包括用户名、密码、过期时间和私钥(key).and().csrf().disable() // 关闭csrf跨站请求伪造防护.exceptionHandling().accessDeniedPage("/unauth.html"); // 配置没有权限访问的自定义页面}

https://zhhll.icu/2021/框架/springSecurity/2.过滤web请求/

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 基于微信小程序+SpringBoot+Vue的青少年科普教学系统平台(带1w+文档)
  • 【PPT把当前页输出为图片】及【PPT导出图片模糊】的解决方法(sci论文图片清晰度)
  • 深入理解 Java 类加载机制:Arthas classloader 命令解析
  • .NET C# 配置 Options
  • Centos7_Minimal安装Cannot find a valid baseurl for repo: base/7/x86_6
  • 代码随想录第五十九天 | 115.不同的子序列,583. 两个字符串的删除操作, 72. 编辑距离
  • 自学Java第11Day
  • LLM推理优化
  • 深度学习 —— 个人学习笔记6(权重衰减)
  • 价格战再起:OpenAI 发布更便宜、更智能的 GPT-4o Mini 模型|TodayAI
  • 前端设计模式面试题汇总
  • c++ primer plus 第16章string 类和标准模板库, 泛型编程----为何使用迭代器
  • 面试题 33. 二叉搜索树的后序遍历序列
  • GD32 MCU上电跌落导致启动异常如何解决
  • 《简历宝典》18 - 简历中“技术能力”,如何丰满且有层次,Java篇
  • Apache Zeppelin在Apache Trafodion上的可视化
  • conda常用的命令
  • FastReport在线报表设计器工作原理
  • Gradle 5.0 正式版发布
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • isset在php5.6-和php7.0+的一些差异
  • JWT究竟是什么呢?
  • open-falcon 开发笔记(一):从零开始搭建虚拟服务器和监测环境
  • windows-nginx-https-本地配置
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 当SetTimeout遇到了字符串
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 运行时添加log4j2的appender
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • # 职场生活之道:善于团结
  • #laravel部署安装报错loadFactoriesFrom是undefined method #
  • (~_~)
  • (2)STM32单片机上位机
  • (21)起落架/可伸缩相机支架
  • (Windows环境)FFMPEG编译,包含编译x264以及x265
  • (纯JS)图片裁剪
  • (附源码)ssm学生管理系统 毕业设计 141543
  • (算法)Game
  • (续)使用Django搭建一个完整的项目(Centos7+Nginx)
  • (转)Groupon前传:从10个月的失败作品修改,1个月找到成功
  • (转)甲方乙方——赵民谈找工作
  • (转)原始图像数据和PDF中的图像数据
  • .md即markdown文件的基本常用编写语法
  • .Net OpenCVSharp生成灰度图和二值图
  • .NET WPF 抖动动画
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • @开发者,一文搞懂什么是 C# 计时器!
  • [ C++ ] STL_vector -- 迭代器失效问题
  • [ C++ ] template 模板进阶 (特化,分离编译)
  • [APIO2012] 派遣 dispatching
  • [AX]AX2012 SSRS报表Drill through action
  • [bzoj1038][ZJOI2008]瞭望塔
  • [C++]:for循环for(int num : nums)