【个人版】SpringBoot下Spring-Security自定义落地篇【三】

2023-12-14 11:12

本文主要是介绍【个人版】SpringBoot下Spring-Security自定义落地篇【三】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

背景: 前两篇文章将spring-security的设计架构、核心类、配置及构建过程基本过了一遍,其实很偏理论,如果对源码不感兴趣或项目使用不深,基本可以忽略,毕竟完全理解可能也不会用到,时间长也忘掉了。但是如果你想对代码进行微调,或者写出自己想要的设计效果,那么读一读还是很有必要,毕竟开发过程就是一个学习的过程。本篇是在参考遍地继承WebSecurityConfigurerAdapter的方案上,再加上自身阅读源码后的理解,结合自身需求而尝试出来的。

Spring-Security全局导读:
1、Security核心类设计
2、HttpSecurity结构和执行流程解读
3、Spring-Security个人落地篇

ps1:WebSecurityConfigurerAdapter在较新的版本中都已经被标注过期了,这也是我读源码时尝试自己尝试新方案的动机之一
ps2: 落地方案其实和最新官方推荐的方案很接近,因为我也是从自动配置类中的SecurityFilterChain的创建过程而猜想过来的
ps3:强烈建议阅读松哥之前写的security系列文章,看看这一篇就知道他的水平了
ps4:如果有时间&有想法,自己写一些试试,很久以前粗略看过松哥Security系列的一部分文章,当时觉得自己懂了,不知过了多久,已经完全忘记基础概念了。

废话过多,以下为个人输出(简略篇):
一、POM依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.14</version><relativePath/> </parent><groupId></groupId><artifactId></artifactId><version></version><name></name><description></description><properties><java.version></java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>compile</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

二、自定义拦截及授权封装类

/*** 1、CustomAuthenticationProvider等其它内部类不能设置为静态类* 2、CustomUsernamePasswordAuthenticationFilter必须重写afterPropertiesSet方法并忽略管理器校验*/
@Component
@ConditionalOnProperty(value = "password.enable", havingValue = "true", matchIfMissing = true)
public class CustomAuthenticationContext {@Componentprivate class CustomAuthenticationProvider implements AuthenticationProvider {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;if ("test".equals(token.getPrincipal().toString()) && "test".equals(token.getCredentials().toString())) {return UsernamePasswordAuthenticationToken.authenticated("test", null, null);}throw new BadCredentialsException("账号信息错误");}@Overridepublic boolean supports(Class<?> authentication) {return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);}}@Componentprivate class CustomUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();private ObjectMapper objectMapper;public CustomUsernamePasswordAuthenticationFilter() {super(new AntPathRequestMatcher("/user/login", "POST"));}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {InputStream content = request.getInputStream();User user = objectMapper.readValue(content, User.class);Set<ConstraintViolation<User>> validate = validator.validate(user, Default.class);if (validate.isEmpty()) {UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(user.getName(), user.getPassword());authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));return this.getAuthenticationManager().authenticate(authRequest);}throw new BadCredentialsException("用户名或密码错误");}@Autowiredvoid init(CustomAuthResult authResult, ObjectMapper objectMapper) {this.objectMapper = objectMapper;setAuthenticationSuccessHandler(authResult);setAuthenticationFailureHandler(authResult);}@Override// 后期统一设置,未重写则实例创建后校验报错public void afterPropertiesSet() {}}@Dataprivate static class User {@NotBlankprivate String name;@NotBlankprivate String password;}	}

说明:
1、自定义鉴权中,Filter及AuthenticationProvider通常是一对一的,此处封装为一个类,并用条件注解修饰,避免多场景下的鉴权组合造成的代码混乱(虽然此类场景通常不会有太大的变更)
2、此块逻辑其实可以放到controller中,但注意授权上下文的控制及HttpSecurity的设置

三、Security框架配置入口类

@Configuration
public class SecurityFilterChainConfiguration {@Autowired// HttpSecurity默认是多例的,此处如果多个方法调用,必须唯一private HttpSecurity httpSecurity;// 参数列表可通过自定义类上条件注解控制// 单个类中同时存在多个@Autowired,执行顺序不固定// 这两个类是一体的,可以封装在一起,不用搞得太零散@Autowiredvoid authenticationManager(List<AuthenticationProvider> customProviders, List<AbstractAuthenticationProcessingFilter> customProcessingFilter) {// 自封装授权管理器,没有使用系统AuthenticationManagerBuilder创建的管理器AuthenticationManager authenticationManager = new ProviderManager(customProviders);for (AbstractAuthenticationProcessingFilter filter : customProcessingFilter) {filter.setAuthenticationManager(authenticationManager);// UsernamePasswordAuthenticationFilter.class为系统内置FilterhttpSecurity.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);}}@BeanSecurityFilterChain securityFilterChain(CustomAuthResult authResult) throws Exception {/** 此块HttpSecurity链式配置包含三块内容* 1、csrf会在response中添加token header,以避免非原始请求客户端伪造访问* 2、关闭默认的表单登录,所有鉴权逻辑自定义* 3、针对logout、异常等场景细节进行配置*/httpSecurity.csrf().disable()// 如果自定义授权了,表单登录可以关闭,通常用于前后台分离项目.formLogin().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()// 这块是为在controller中做授权校验而放开的,此场景后续补充.antMatchers(HttpMethod.POST, "/doLogin").permitAll().anyRequest().authenticated().and().logout().logoutSuccessHandler(authResult).permitAll()// 设置访问未授权资源的处理器.and().exceptionHandling().authenticationEntryPoint(authResult);// 手工build,没有借助WebSecurity类的管理return httpSecurity.build();}
}

四、响应封装合体类

@Component
public class CustomAuthResult implements AuthenticationFailureHandler, AuthenticationSuccessHandler, AuthenticationEntryPoint, LogoutSuccessHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");response.setStatus(HttpStatus.UNAUTHORIZED.value());response.getWriter().write("{\"code\":\"1004\",\"msg\":\"用户名或密码错误\"}");response.getWriter().flush();response.getWriter().close();}@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");response.getWriter().write("{\"code\":\"1000\",\"msg\":\"登录成功\"}");response.getWriter().flush();response.getWriter().close();}@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");response.setStatus(HttpStatus.FORBIDDEN.value());response.getWriter().write("{\"code\":\"1001\",\"msg\":\"用户未登录\"}");response.getWriter().flush();response.getWriter().close();}@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");response.getWriter().write("{\"code\":\"1003\",\"msg\":\"成功退出\"}");response.getWriter().flush();response.getWriter().close();}
}

说明:此类自己调试随便建的,生产项目需要有严格而准确的封装和处理

简单自定义使用,以上就足够了,相关注意事项也在注释中说明,不管是继承WebSecurityConfigurerAdapter的方式,还是其他方式,核心类的执行流程其实是不变的,变的只是配置方式或组合方式的外皮,所以把基础概念了解清楚了,不管是spring5还是spring6的版本变化,基本不会有太大的挑战。

PS:
1、关于用户权限数据管理逻辑,框架层提供了UserDetailsService接口及对应内存&数据库的默认实现,这个需求差异较大,如验证码登录,此处不再展开,直接在验证逻辑处写死配置。
2、在新版本中(参考依赖),不管是继承WebSecurityConfigurerAdapter的方式,还是哪种方式,都不需要再自行使用@EnableWebSecurity注解在类上进行标注了,自动配置类中已告知。

附Adapter模式简化配置版:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowired// 代码参考上述方案定义private CustomAuthResult authResult;@Autowired// AuthenticationManager配置类,复用全局AuthenticationManagerprivate AuthenticationConfiguration configuration;@Override// 适配器模式只需要重写此方法,完成内部过滤器链配置protected void configure(HttpSecurity http) throws Exception {// 自定义安全管理过滤器,对应鉴权和参数封装逻辑此处忽略http.addFilterBefore(adaptUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);http.csrf().disable().formLogin().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and().logout().logoutSuccessHandler(authResult).permitAll().and().exceptionHandling().authenticationEntryPoint(authResult);}@Bean// 自定义Filter内部有其他Autowired注解需要处理,所以需要发布到容器// 如果手工set,可以考虑不发布到spring容器中,限制其作用域范围AdaptUsernamePasswordAuthenticationFilter adaptUsernamePasswordAuthenticationFilter() throws Exception {AuthenticationManager authenticationManager = configuration.getAuthenticationManager();AdaptUsernamePasswordAuthenticationFilter adaptUsernamePasswordAuthenticationFilter = new AdaptUsernamePasswordAuthenticationFilter("/user/login");adaptUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManager);return adaptUsernamePasswordAuthenticationFilter;}@Bean// 自定义授权管理器,代码和上述方案定义类一致,但上述是内部类,包路径不一致public AuthenticationProvider authenticationProvider() {return new CustomAuthenticationProvider();}
}

可以看到继承WebSecurity适配器的代码同样也很简单,核心还是HttpSecurity的构建,不过第一种方案灵活性更高,我们自己组织和封装的可能性更好,体现模块化的思想,适配方式已经标注过期,最新版本已经删除,可作参考。

这篇关于【个人版】SpringBoot下Spring-Security自定义落地篇【三】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav