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

spring boot security 自定义AuthenticationProvider

spring boot security 自定义AuthenticationProvider

基于 spring boot 3.x

场景实现 手机验证码登陆

实现

CaptureCodeAuthenticationFilter

public class CaptureCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private static final String DEFAULT_LOGIN_URL = "/capture/login";private static final String DEFAULT_PHONE_NAME = "phone";private static final String DEFAULT_CODE_NAME = "code";private String codeParamName = DEFAULT_CODE_NAME;private String phoneParamName = DEFAULT_PHONE_NAME;public CaptureCodeAuthenticationFilter(AuthenticationManager authenticationManager) {super(DEFAULT_LOGIN_URL, authenticationManager);}public CaptureCodeAuthenticationFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {super(defaultFilterProcessesUrl, authenticationManager);}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {if (!request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());}String phone = obtainPhone(request);phone = (phone != null) ? phone.trim() : "";String code = obtainCaptureCode(request);code = (code != null) ? code : "";CaptureCodeAuthenticationToken token = new CaptureCodeAuthenticationToken(phone, code);return this.getAuthenticationManager().authenticate(token);}protected String obtainCaptureCode(HttpServletRequest request) {return request.getParameter(this.codeParamName);}protected String obtainPhone(HttpServletRequest request) {return request.getParameter(this.phoneParamName);}
}

CaptureCodeAuthenticationToken

public class CaptureCodeAuthenticationToken extends UsernamePasswordAuthenticationToken {public CaptureCodeAuthenticationToken(Object principal, Object credentials) {super(principal, credentials);}
}

CaptureCodeAuthenticationProvider

public class CaptureCodeAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {@Overridepublic boolean supports(Class<?> authentication) {return (CaptureCodeAuthenticationToken.class.isAssignableFrom(authentication));}@Overrideprotected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {if (authentication.getPrincipal()==null){throw new BadCredentialsException("Bad credentials "+ authentication.getPrincipal().toString());}if (authentication.getCredentials()==null){throw new BadCredentialsException("Bad credentials "+ authentication.getPrincipal().toString());}}@Overrideprotected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {CaptureCodeAuthenticationToken token = (CaptureCodeAuthenticationToken) authentication;if (!token.getPrincipal().equals("tom")){throw new UsernameNotFoundException("username not fund!");}UserDetails user = User.withUsername("tom").password("tom").build();return user;}}

配置 DefaultSecurityConfig

@Configuration
@EnableWebSecurity
public class DefaultSecurityConfig {@Autowiredprivate ObjectMapper objectMapper;@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(request -> request.anyRequest().authenticated());http.formLogin(Customizer.withDefaults());http.csrf(AbstractHttpConfigurer::disable);http.addFilterBefore(captureCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);return http.build();}public CaptureCodeAuthenticationFilter captureCodeAuthenticationFilter() {ProviderManager providerManager = new ProviderManager(new CaptureCodeAuthenticationProvider());CaptureCodeAuthenticationFilter filter =new CaptureCodeAuthenticationFilter(providerManager);filter.setAuthenticationSuccessHandler((request, response, authentication) -> {response.setStatus(HttpServletResponse.SC_OK);response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);response.getWriter().write(objectMapper.writeValueAsString(Result.ok("认证成功")));response.getWriter().flush();});filter.setAuthenticationFailureHandler((request, response, exception) -> {response.setStatus(HttpServletResponse.SC_OK);response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);response.getWriter().write(objectMapper.writeValueAsString(Result.ok("认证失败")));response.getWriter().flush();});return filter;}@Beanpublic UserDetailsService users(PasswordEncoder passwordEncoder) {UserDetails user = User.withUsername("admin").password(passwordEncoder.encode("admin")).build();return new InMemoryUserDetailsManager(user);}@Beanpublic PasswordEncoder encoder() {return new BCryptPasswordEncoder();}}

相关文章:

spring boot security 自定义AuthenticationProvider

spring boot security 自定义AuthenticationProvider 基于 spring boot 3.x 场景实现 手机验证码登陆 实现 CaptureCodeAuthenticationFilter public class CaptureCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private static final Strin…...

某电力设计公司绩效考核优化项目成功案例纪实

——引入角色定位考核法&#xff0c;建立多维度评价体系&#xff0c;支持业务转型后的客观评价 【客户行业】电力行业 【问题类型】绩效考核 【客户背景及现状分析】 某电力设计公司成立于2000年左右&#xff0c;是一家从事输变电工程勘察、设计、咨询的专业公司&#xff0c…...

力扣371周赛

力扣第371场周赛 找出强数对的最大异或值 I 枚举 class Solution { public:int maximumStrongPairXor(vector<int>& a) {int n a.size() , res 0;for(int i 0 ; i < n ; i ){for(int j 0 ; j < n ; j ){if(abs(a[i]-a[j])<min(a[i],a[j])){int c (a…...

Python之字符串、正则表达式练习

目录 1、输出随机字符串2、货币的转换&#xff08;字符串 crr107&#xff09;3、凯撒加密&#xff08;book 实验 19&#xff09;4、字符替换5、检测字母或数字6、纠正字母7、输出英文中所有长度为3个字母的单词 1、输出随机字符串 编写程序&#xff0c;输出由英文字母大小写或…...

Transmit :macOS 好用的 Ftp/SFtp 工具

Transmit 是一种功能强大的 FTP/SFTP/WebDAV 客户端软件&#xff0c;是一个 Mac OS X 平台上设计的文件传输软件。它由 Panic&#xff08;一家以软件工具为主的公司&#xff09;开发和维护&#xff0c;是一款非常受欢迎且易于使用的软件&#xff0c;而且被广泛认为是 Mac OS X …...

【Github】git clone命令下载文件中途停止

方法一&#xff1a; 使用git clone命令下载github上的源代码时&#xff0c;有时文件下载到一定百分比时就停止不动&#xff0c; 这是因为我们所下载的文件很大&#xff0c;超过了git预先分配的Postbuffer容量&#xff0c;所以一直卡在那里。可以使用以下命令查看当前Postbuffe…...

Clickhouse学习笔记(10)—— 查询优化

单表查询 Prewhere 替代 where prewhere与where相比&#xff0c;在过滤数据的时候会首先读取指定的列数据&#xff0c;来判断数据过滤&#xff0c;等待数据过滤之后再读取 select 声明的列字段来补全其余属性 简单来说就是先过滤再查询&#xff0c;而where过滤是先查询出对应…...

[量化投资-学习笔记012]Python+TDengine从零开始搭建量化分析平台-策略回测

上一章节《MACD金死叉策略回测》中&#xff0c;对平安银行这只股票&#xff0c;按照金死叉策略进行了回测。 但通常我们的股票池中有许多股票&#xff0c;每完成一个交易策略都需要对整个股票池进行回测。 下面使用简单的轮询&#xff0c;对整个股票池进行回测。 # 计算单只…...

MySQL 查看 event 执行记录

文章目录 1. 查看 EVENT 执行记录2. 示例3. 结论 MySQL 是一款流行的关系型数据库管理系统&#xff0c;它提供了许多功能来帮助用户管理和操作数据库。其中之一就是 EVENT事件&#xff0c;它允许用户在特定的时间间隔内自动执行指定的操作&#xff0c;类似于计划任务。 在使用 …...

开发知识点-Vue-Electron

Electron ElectronVue打包.exe桌面程序 ElectronVue打包.exe桌面程序 为了不报错 卸载以前的脚手架 npm uninstall -g vue-cli安装最新版脚手架 cnpm install -g vue/cli创建一个 vue 随便起个名 vue create electron-vue-example (随便起个名字electron-vue-example)进入 创建…...

【线性代数】反求矩阵A

...

MyBatis 中的 foreach 的用法

本文将介绍 MyBatis 中的 <foreach> 标签的灵活应用&#xff0c;并结合财经领域的数据处理场景&#xff0c;阐述其在财经系统开发中的重要性和应用价值。 MyBatis中的<foreach>标签简介 MyBatis 是一个优秀的持久层框架&#xff0c;它简化了数据库操作的流程&…...

交叉编译 mysql-connector-c

下载 mysql-connector-c $ wget https://downloads.mysql.com/archives/get/p/19/file/mysql-connector-c-6.1.5-src.tar.gz 注意&#xff1a;mysql-connector 的页面有很多版本&#xff0c;在测试过程中发现很多默认编译有问题&#xff0c;其中上面的 6.1.5 的版本呢是经过测…...

企业如何选择正确的存储服务器租用?

数据时代的发展&#xff0c;让越来越多的企业选择使用存储服务器来存储数据&#xff0c;今天小编就带大家了解一下企业应该怎么正确的选择存储服务器吧&#xff0c;要关注哪些方面的问题呢&#xff1f; 第一点肯定是看自己的需求&#xff0c;不论是选择什么服务器最重要的一点就…...

45.跳跃游戏II

45.跳跃游戏II 题目描述&#xff1a;给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说&#xff0c;如果你在 nums[i] 处&#xff0c;你可以跳转到任意 nums[i j] 处: 0 < j < nums[i]i …...

css style、css color 转 UIColor

你能看过来&#xff0c;就说明这个问题很好玩&#xff01;IT开发是一个兴趣&#xff0c;更是一个挑战&#xff01;兴趣使你工作有热情。挑战使让你工作充满刺激拉满的状态&#xff01;我们日复一日年复一年的去撸代码&#xff0c;那些普普通通的功能代码&#xff0c;已经厌倦了…...

C++(20):typename声明类的子类型的简化

C++:typename声明类的子类型_风静如云的博客-CSDN博客 介绍了某些时候需要使用typename来告诉编译器,这是一个类的类型。 C++20简化了对typename的需求,对于明显是类型的地方,可以不再使用typename进行说明: #include <iostream> #include <string>using na…...

一个java文件的JVM之旅

准备 我是小C同学编写得一个java文件&#xff0c;如何实现我的功能呢&#xff1f;需要去JVM(Java Virtual Machine)这个地方旅行。 变身 我高高兴兴的来到JVM&#xff0c;想要开始JVM之旅&#xff0c;它确说&#xff1a;“现在的我还不能进去&#xff0c;需要做一次转换&#x…...

C# wpf 实现任意控件(包括窗口)更多拖动功能

系列文章目录 第一章 Grid内控件拖动 第二章 Canvas内控件拖动 第三章 任意控件拖动 第四章 窗口拖动 第五章 附加属性实现任意拖动 第六章 拓展更多拖动功能&#xff08;本章&#xff09; 文章目录 系列文章目录前言一、添加的功能1、任意控件MoveTo2、任意控件DragMove3、边…...

一种ADC采样算法,中位值平均滤波+递推平均滤波

前言 在实际AD采集场景中&#xff0c;会出现周期性变化和偶然脉冲波动干扰对AD采集的影响 这里使用中位值平均滤波递推平均滤波的结合 参考前人写好的代码框架&#xff0c;也参考博主GuYH_下面这篇博客&#xff0c;在此基础上稍作修改&#xff0c;写出这篇博客&#xff0c;能…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

基础测试工具使用经验

背景 vtune&#xff0c;perf, nsight system等基础测试工具&#xff0c;都是用过的&#xff0c;但是没有记录&#xff0c;都逐渐忘了。所以写这篇博客总结记录一下&#xff0c;只要以后发现新的用法&#xff0c;就记得来编辑补充一下 perf 比较基础的用法&#xff1a; 先改这…...

【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)

升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点&#xff0c;但无自动故障转移能力&#xff0c;Master宕机后需人工切换&#xff0c;期间消息可能无法读取。Slave仅存储数据&#xff0c;无法主动升级为Master响应请求&#xff…...

爬虫基础学习day2

# 爬虫设计领域 工商&#xff1a;企查查、天眼查短视频&#xff1a;抖音、快手、西瓜 ---> 飞瓜电商&#xff1a;京东、淘宝、聚美优品、亚马逊 ---> 分析店铺经营决策标题、排名航空&#xff1a;抓取所有航空公司价格 ---> 去哪儿自媒体&#xff1a;采集自媒体数据进…...

华为OD最新机试真题-数组组成的最小数字-OD统一考试(B卷)

题目描述 给定一个整型数组,请从该数组中选择3个元素 组成最小数字并输出 (如果数组长度小于3,则选择数组中所有元素来组成最小数字)。 输入描述 行用半角逗号分割的字符串记录的整型数组,0<数组长度<= 100,0<整数的取值范围<= 10000。 输出描述 由3个元素组成…...

数据结构:递归的种类(Types of Recursion)

目录 尾递归&#xff08;Tail Recursion&#xff09; 什么是 Loop&#xff08;循环&#xff09;&#xff1f; 复杂度分析 头递归&#xff08;Head Recursion&#xff09; 树形递归&#xff08;Tree Recursion&#xff09; 线性递归&#xff08;Linear Recursion&#xff09;…...

消防一体化安全管控平台:构建消防“一张图”和APP统一管理

在城市的某个角落&#xff0c;一场突如其来的火灾打破了平静。熊熊烈火迅速蔓延&#xff0c;滚滚浓烟弥漫开来&#xff0c;周围群众的生命财产安全受到严重威胁。就在这千钧一发之际&#xff0c;消防救援队伍迅速行动&#xff0c;而豪越科技消防一体化安全管控平台构建的消防“…...

ThreadLocal 源码

ThreadLocal 源码 此类提供线程局部变量。这些变量不同于它们的普通对应物&#xff0c;因为每个访问一个线程局部变量的线程&#xff08;通过其 get 或 set 方法&#xff09;都有自己独立初始化的变量副本。ThreadLocal 实例通常是类中的私有静态字段&#xff0c;这些类希望将…...