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

新版本Spring Security 2.7 + 用法,直接旧正版粘贴

一、以前的用法:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}

WebSecurityConfigurerAdapter 已经过时了,新版本已经不用这个了。

二、现在的用法

使用@EnableWebSecurity注解

@Configuration
@EnableWebSecurity
public class SecurityConfig{//配置密码加密器@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}/*** 安全配置*/@BeanSecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/user/login").anonymous().anyRequest().authenticated();return http.build();}/*** 认证管理器,登录的时候参数会传给 authenticationManager*/@Bean(name = BeanIds.AUTHENTICATION_MANAGER)public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {return authenticationConfiguration.getAuthenticationManager();}
}

三、其他的一些配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig {@Resourceprivate CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;@Resourceprivate CustomAuthenticationFailureHandler customAuthenticationFailureHandler;@Resourceprivate CustomAuthenticationEntryPoint customAuthenticationEntryPoint;@Resourceprivate CustomLogoutHandler customLogoutHandler;@Resourceprivate CustomLogoutSuccessHandler customLogoutSuccessHandler;@Resourceprivate CustomAccessDeniedHandler customAccessDeniedHandler;@Resourceprivate SecurityProperties securityProperties;@Resourceprivate JwtStoreService jwtStoreService;@Resourceprivate UserDetailsServiceImpl userDetailsService;@Resourceprivate AuthenticationConfiguration authenticationConfiguration;/*** 静态文件放行*/@Beanpublic WebSecurityCustomizer webSecurityCustomizer() {return (web) -> web.ignoring().antMatchers(securityProperties.getStaticPaths());}/*** 取消ROLE_前缀*/@Beanpublic GrantedAuthorityDefaults grantedAuthorityDefaults() {// Remove the ROLE_ prefixreturn new GrantedAuthorityDefaults("");}/*** 设置密码编码器*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}/*** 设置中文配置*/@Beanpublic ReloadableResourceBundleMessageSource messageSource() {ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");return messageSource;}/*** 认证管理器,登录的时候参数会传给 authenticationManager*/@Beanpublic AuthenticationManager authenticationManager() throws Exception {return authenticationConfiguration.getAuthenticationManager();}/*** 设置默认认证提供*/@Beanpublic DaoAuthenticationProvider daoAuthenticationProvider() {final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();authenticationProvider.setUserDetailsService(userDetailsService);authenticationProvider.setPasswordEncoder(passwordEncoder());return authenticationProvider;}/*** 安全配置*/@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationConfiguration authenticationConfiguration) throws Exception {// 表单http.formLogin()// 登录成功处理器.successHandler(customAuthenticationSuccessHandler)// 登录错误处理器.failureHandler(customAuthenticationFailureHandler).and()//添加登录逻辑拦截器,不使用默认的UsernamePasswordAuthenticationFilter.addFilterBefore(new CustomUsernamePasswordAuthenticationFilter(authenticationManager(),customAuthenticationSuccessHandler,customAuthenticationFailureHandler), UsernamePasswordAuthenticationFilter.class)//添加token验证过滤器.addFilterBefore(new JwtAuthenticationFilter(jwtStoreService), LogoutFilter.class);//退出http.logout()// URL.logoutUrl("/user/logout")// 登出处理.addLogoutHandler(customLogoutHandler)// 登出成功处理.logoutSuccessHandler(customLogoutSuccessHandler);//拦截设置http.authorizeRequests()//公开以下urls.antMatchers(securityProperties.getPublicPaths()).permitAll()//其他路径必须验证.anyRequest().authenticated();//异常处理http.exceptionHandling()// 未登录处理.authenticationEntryPoint(customAuthenticationEntryPoint)// 无权限处理.accessDeniedHandler(customAccessDeniedHandler);//关闭sessionhttp.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);// 关闭corshttp.cors().disable();// 关闭csrfhttp.csrf().disable();// 关闭headershttp.headers().frameOptions().disable();return http.build();}
}
————————
如觉不错,随手点赞,关注,收藏(* ̄︶ ̄),谢谢~~
http://www.lryc.cn/news/235596.html

相关文章:

  • JVM——类加载器(JDK8及之前,双亲委派机制)
  • (七)什么是Vite——vite优劣势、命令
  • vue之Error: Unknown option: .devServer.
  • 基于ssm的房屋租售网站(有报告)。Javaee项目,ssm项目。
  • LeeCode AutoX-4 计算几何
  • Vue3 动态设置 ref
  • fast lio 2 保存每一帧的点云PCD和里程计矩阵 Odom 在txt文件
  • 当前主流DDos方式有哪几类
  • 神经网络常见评价指标AUROC(AUC-ROC)、AUPR(AUC-PR)
  • Apache Doris安装部署
  • Excel查询时用vlookup或者xlookup时,虽然用的参数选择的是精确匹配,但是发现不能区分大小写,应该如何解决?
  • 4种经典的限流算法
  • <MySQL> 什么是数据库事务?事务该如何使用?
  • Linux 网络:PMTUD 简介
  • BatchNormalization:解决神经网络中的内部协变量偏移问题
  • DAC实验(DAC 输出三角波实验)(DAC 输出正弦波实验)
  • 许多网友可能还不知道,升级到Windows 11其实没那么复杂,只要符合几个条件可以了
  • ubuntu下载conda
  • 重磅 | 进一步夯实生态建设,朗思科技与阿里龙蜥完成兼容性认证
  • Qt给控件添加图片
  • 3.6-Dockerfile语法梳理及最佳实践
  • springboot集成nacos并实现自动刷新
  • java面试八股文2023完整版详解110题附带答案
  • 微服务实战系列之Token
  • DRF纯净版项目搭建和配置
  • AUTODL云服务器使用大致步骤(适合本人版)
  • 无需云盘,不限流量实现Zotero跨平台同步:内网穿透+私有WebDAV服务器
  • 简朴博客系统测试报告
  • Qt遇到常见问题记录
  • pm2在Windows环境中的使用