当前位置: 首页 > 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;能…...

7.4.分块查找

一.分块查找的算法思想&#xff1a; 1.实例&#xff1a; 以上述图片的顺序表为例&#xff0c; 该顺序表的数据元素从整体来看是乱序的&#xff0c;但如果把这些数据元素分成一块一块的小区间&#xff0c; 第一个区间[0,1]索引上的数据元素都是小于等于10的&#xff0c; 第二…...

应用升级/灾备测试时使用guarantee 闪回点迅速回退

1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间&#xff0c; 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点&#xff0c;不需要开启数据库闪回。…...

从WWDC看苹果产品发展的规律

WWDC 是苹果公司一年一度面向全球开发者的盛会&#xff0c;其主题演讲展现了苹果在产品设计、技术路线、用户体验和生态系统构建上的核心理念与演进脉络。我们借助 ChatGPT Deep Research 工具&#xff0c;对过去十年 WWDC 主题演讲内容进行了系统化分析&#xff0c;形成了这份…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

ArcGIS Pro制作水平横向图例+多级标注

今天介绍下载ArcGIS Pro中如何设置水平横向图例。 之前我们介绍了ArcGIS的横向图例制作&#xff1a;ArcGIS横向、多列图例、顺序重排、符号居中、批量更改图例符号等等&#xff08;ArcGIS出图图例8大技巧&#xff09;&#xff0c;那这次我们看看ArcGIS Pro如何更加快捷的操作。…...

论文笔记——相干体技术在裂缝预测中的应用研究

目录 相关地震知识补充地震数据的认识地震几何属性 相干体算法定义基本原理第一代相干体技术&#xff1a;基于互相关的相干体技术&#xff08;Correlation&#xff09;第二代相干体技术&#xff1a;基于相似的相干体技术&#xff08;Semblance&#xff09;基于多道相似的相干体…...

2025年渗透测试面试题总结-腾讯[实习]科恩实验室-安全工程师(题目+回答)

安全领域各种资源&#xff0c;学习文档&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具&#xff0c;欢迎关注。 目录 腾讯[实习]科恩实验室-安全工程师 一、网络与协议 1. TCP三次握手 2. SYN扫描原理 3. HTTPS证书机制 二…...

论文阅读:LLM4Drive: A Survey of Large Language Models for Autonomous Driving

地址&#xff1a;LLM4Drive: A Survey of Large Language Models for Autonomous Driving 摘要翻译 自动驾驶技术作为推动交通和城市出行变革的催化剂&#xff0c;正从基于规则的系统向数据驱动策略转变。传统的模块化系统受限于级联模块间的累积误差和缺乏灵活性的预设规则。…...

Spring Security 认证流程——补充

一、认证流程概述 Spring Security 的认证流程基于 过滤器链&#xff08;Filter Chain&#xff09;&#xff0c;核心组件包括 UsernamePasswordAuthenticationFilter、AuthenticationManager、UserDetailsService 等。整个流程可分为以下步骤&#xff1a; 用户提交登录请求拦…...

软件工程 期末复习

瀑布模型&#xff1a;计划 螺旋模型&#xff1a;风险低 原型模型: 用户反馈 喷泉模型:代码复用 高内聚 低耦合&#xff1a;模块内部功能紧密 模块之间依赖程度小 高内聚&#xff1a;指的是一个模块内部的功能应该紧密相关。换句话说&#xff0c;一个模块应当只实现单一的功能…...