springsecurity6使用

2024-02-14 16:04
文章标签 使用 springsecurity6

本文主要是介绍springsecurity6使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

spring security 中的类 :

  • AuthenticationManager : 实现类:ProviderManager
    管理很多的 provider ,,, 经常使用的,DaoAuthenticationProvider , 这个要设置一个 UserDetailService , 查找数据库,,loadUserByUsername() 查找出数据库中的对象,,然后进行比对
spring security 中的配置

配置spring security 也就是配置 过滤器链,,spring security 他有默认的过滤器链,,,通过HttpSecurity 中的 build()方法,会返回一个默认的有拦截的过滤器链
我们一般都是在这个原本的过滤器链上面修改,,而不是重新创建自己的过滤器链,,

/*** 过滤器*  : 配置过滤器链*  DispatchServlet**  DefaultLoginPageGeneratingFilter : 默认登录页面过滤器*  DefaultLogoutPageGeneratingFilter : 默认注销页面过滤器*  BasicAuthenticationFilter : 请求头认证过滤器*//*** 配置过滤器链  SecurityFilterChain,,spring security 所有功能都是通过过滤器链来提供*/@BeanSecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {// 拦截所有,,经过某些过滤器
//        return new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"));// 默认的过滤器链
//        return http.build();http.authorizeHttpRequests(p->p.anyRequest().authenticated()).formLogin(f->f.usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login").successHandler((req,resp,auth)->{resp.setContentType("application/json;charset=utf-8");Hr hr = (Hr) auth.getPrincipal();hr.setPassword(null);resp.getWriter().write(new ObjectMapper().writeValueAsString(RespBean.ok("登录成功",hr)));}).failureHandler((req,resp,e)->{resp.setContentType("application/json;charset=utf-8");RespBean error = RespBean.error("登录失败");if (e instanceof BadCredentialsException){error.setMessage("密码错误");}else if (e instanceof DisabledException){error.setMessage("用户被禁用");}else if (e instanceof LockedException){error.setMessage("账户被锁定");}else if (e instanceof AccountExpiredException){error.setMessage("账户过期");}else if(e instanceof CredentialsExpiredException){error.setMessage("密码过期");}resp.getWriter().write(new ObjectMapper().writeValueAsString(error));})).csrf(c->c.disable())//异常处理.exceptionHandling(e->e.authenticationEntryPoint((req,resp,ex)->{resp.setContentType("application/json;charset=utf-8");resp.setStatus(401);RespBean error = RespBean.error("尚未登陆,请登录");resp.getWriter().write(new ObjectMapper().writeValueAsString(error));}));// 加到 UsernamePasswordAuthenticationFilter前面http.addFilterBefore(jsonFilter(), UsernamePasswordAuthenticationFilter.class);return  http.build();/*** spring security 默认key-value* UsernamePasswordAuthenticationFilter*/}

UsernamePasswordAuthenticationFilter : 这个是拦截提交的用户名密码的拦截器,,,里面有个attemptAuthentication() 去获取前端传入的用户名密码,
在这里插入图片描述
根据request获取的参数,,,
然而,我们需要通过json传参,,就需要重写这个方法,,并将自己的过滤器加入到spring security的过滤器链中,,

/*** 登录传递json*/
public class JsonFilter extends UsernamePasswordAuthenticationFilter {@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (!request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());}String contentType = request.getContentType();if (contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)){// 前端传入的是jsontry {// 通过io流,去解析请求体参数,,,比如:文件,json,,,   key-value也可以通过io流获取Hr hr = new ObjectMapper().readValue(request.getInputStream(), Hr.class);String username = hr.getUsername();String password = hr.getPassword();UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,password);// Allow subclasses to set the "details" propertysetDetails(request, authRequest);// 获取认证管理器去认证return this.getAuthenticationManager().authenticate(authRequest);} catch (IOException e) {throw new RuntimeException(e);}}else{//  key-valuereturn super.attemptAuthentication(request,response);}}
}

自己新加的过滤器,需要配置自己的 AuthenticationManager , 和用户信息存放的位置:

   /*** AuthenticationManager :*      实现类:   ProviderManager*      管理很多 provider* @return*/@BeanAuthenticationManager authenticationManager(){DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();daoAuthenticationProvider.setUserDetailsService(hrService);ProviderManager providerManager = new ProviderManager(daoAuthenticationProvider);return providerManager;}

配置了自己的 登录filter,, HttpSecurity中配置的formLogin 就失效了,,,需要自己配置loginProcessingUrl, successHandler,failureHandler等信息,,

需要配置自己的 AuthenticationManager 和表明登录信息的存放位子,,,,因为每一次都会从这个存放位置去找用户信息,,如果找到,表示已登录,如果没找到,就是没有登录

   /*** 配置了  JsonFilter ,,,    httpsecurity 中的 fromLogin就失效了* @return*/JsonFilter jsonFilter(){JsonFilter jsonFilter = new JsonFilter();jsonFilter.setFilterProcessesUrl("/login");jsonFilter.setAuthenticationSuccessHandler((req,resp,auth)->{resp.setContentType("application/json;charset=utf-8");Hr hr = (Hr) auth.getPrincipal();hr.setPassword(null);resp.getWriter().write(new ObjectMapper().writeValueAsString(RespBean.ok("登录成功",hr)));});jsonFilter.setAuthenticationFailureHandler((req,resp,e)->{resp.setContentType("application/json;charset=utf-8");RespBean error = RespBean.error("登录失败");if (e instanceof BadCredentialsException){error.setMessage("密码错误");}else if (e instanceof DisabledException){error.setMessage("用户被禁用");}else if (e instanceof LockedException){error.setMessage("账户被锁定");}else if (e instanceof AccountExpiredException){error.setMessage("账户过期");}else if(e instanceof CredentialsExpiredException){error.setMessage("密码过期");}resp.getWriter().write(new ObjectMapper().writeValueAsString(error));});// 需要设置自己的 AuthenticationManagerjsonFilter.setAuthenticationManager(authenticationManager());/***  每一次都会从 httpSession中获取用户,,如果httpsession中没有用户,就会表示成没有登录,,*  新配置的 filter 需要告知 ,,用户信息存放在哪里,,*/// 自己配置的filter 需要设置 SecurityContextHolder 存储用户的位置jsonFilter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());return jsonFilter;}

这个用户信息可以存在HttpSessionSecurityContextRepositorysession中,,也可以重写类,存放在其他地方,比如redis

spring security 异常处理,,exceptionHandling, 中authenticationEntryPoint,处理登录失败异常
在这里插入图片描述

这篇关于springsecurity6使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/708965

相关文章

如何使用Docker部署FTP和Nginx并通过HTTP访问FTP里的文件

《如何使用Docker部署FTP和Nginx并通过HTTP访问FTP里的文件》本文介绍了如何使用Docker部署FTP服务器和Nginx,并通过HTTP访问FTP中的文件,通过将FTP数据目录挂载到N... 目录docker部署FTP和Nginx并通过HTTP访问FTP里的文件1. 部署 FTP 服务器 (

MySQL 日期时间格式化函数 DATE_FORMAT() 的使用示例详解

《MySQL日期时间格式化函数DATE_FORMAT()的使用示例详解》`DATE_FORMAT()`是MySQL中用于格式化日期时间的函数,本文详细介绍了其语法、格式化字符串的含义以及常见日期... 目录一、DATE_FORMAT()语法二、格式化字符串详解三、常见日期时间格式组合四、业务场景五、总结一、

Python中配置文件的全面解析与使用

《Python中配置文件的全面解析与使用》在Python开发中,配置文件扮演着举足轻重的角色,它们允许开发者在不修改代码的情况下调整应用程序的行为,下面我们就来看看常见Python配置文件格式的使用吧... 目录一、INI配置文件二、YAML配置文件三、jsON配置文件四、TOML配置文件五、XML配置文件

Go使用pprof进行CPU,内存和阻塞情况分析

《Go使用pprof进行CPU,内存和阻塞情况分析》Go语言提供了强大的pprof工具,用于分析CPU、内存、Goroutine阻塞等性能问题,帮助开发者优化程序,提高运行效率,下面我们就来深入了解下... 目录1. pprof 介绍2. 快速上手:启用 pprof3. CPU Profiling:分析 C

MySQL InnoDB引擎ibdata文件损坏/删除后使用frm和ibd文件恢复数据

《MySQLInnoDB引擎ibdata文件损坏/删除后使用frm和ibd文件恢复数据》mysql的ibdata文件被误删、被恶意修改,没有从库和备份数据的情况下的数据恢复,不能保证数据库所有表数据... 参考:mysql Innodb表空间卸载、迁移、装载的使用方法注意!此方法只适用于innodb_fi

Python中conda虚拟环境创建及使用小结

《Python中conda虚拟环境创建及使用小结》本文主要介绍了Python中conda虚拟环境创建及使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们... 目录0.前言1.Miniconda安装2.conda本地基本操作3.创建conda虚拟环境4.激活c

Spring中@Lazy注解的使用技巧与实例解析

《Spring中@Lazy注解的使用技巧与实例解析》@Lazy注解在Spring框架中用于延迟Bean的初始化,优化应用启动性能,它不仅适用于@Bean和@Component,还可以用于注入点,通过将... 目录一、@Lazy注解的作用(一)延迟Bean的初始化(二)与@Autowired结合使用二、实例解

SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)

《SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)》本文介绍了如何在SpringBoot项目中使用Jasypt对application.yml文件中的敏感信息(如数... 目录SpringBoot使用Jasypt对YML文件配置内容进行加密(例:数据库密码加密)前言一、J

Spring Boot 中正确地在异步线程中使用 HttpServletRequest的方法

《SpringBoot中正确地在异步线程中使用HttpServletRequest的方法》文章讨论了在SpringBoot中如何在异步线程中正确使用HttpServletRequest的问题,... 目录前言一、问题的来源:为什么异步线程中无法访问 HttpServletRequest?1. 请求上下文与线

在 Spring Boot 中使用异步线程时的 HttpServletRequest 复用问题记录

《在SpringBoot中使用异步线程时的HttpServletRequest复用问题记录》文章讨论了在SpringBoot中使用异步线程时,由于HttpServletRequest复用导致... 目录一、问题描述:异步线程操作导致请求复用时 Cookie 解析失败1. 场景背景2. 问题根源二、问题详细分