SpringSecurity自定义登录方式
自定义登录:
- 定义Token
- 定义Filter
- 定义Provider
- 配置类中定义登录的接口
- 自定义AuthenticationToken
public class EmailAuthenticationToken extends UsernamePasswordAuthenticationToken{public EmailAuthenticationToken(Object principal, Object credentials) {super(principal, credentials);}public EmailAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {super(principal, credentials, authorities);}
}
- 自定义AuthenticationFilter
public class EmailAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private static final String EMAIL = "email";private static final String EMAIL_CODE = "emailCode";private boolean postOnly = true;public EmailAuthenticationFilter(RequestMatcher requestMatcher) {super(requestMatcher);}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {if (this.postOnly && !request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());} else {Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);String email = map.get(EMAIL);email = email != null ? email : "";email = email.trim();String emailCode = map.get(EMAIL_CODE);emailCode = emailCode != null ? emailCode : "";EmailAuthenticationToken emailAuthenticationToken = new EmailAuthenticationToken(email, emailCode);this.setDetails(request, emailAuthenticationToken);return this.getAuthenticationManager().authenticate(emailAuthenticationToken);}}protected void setDetails(HttpServletRequest request, EmailAuthenticationToken authRequest) {authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));}
}
- 自定义AuthenticationProvider
public class EmailAuthenticationProvider implements AuthenticationProvider {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {EmailAuthenticationToken emailAuthenticationToken = (EmailAuthenticationToken) authentication;String code = emailAuthenticationToken.getCode();String email = (String) emailAuthenticationToken.getPrincipal();if (email.equals("205564122@qq.com") && code.equals("1234")) {SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("wuyu");return new EmailAuthenticationToken(email, null, List.of(simpleGrantedAuthority));}throw new InternalAuthenticationServiceException("认证失败");}@Overridepublic boolean supports(Class<?> authentication) {return EmailAuthenticationToken.class.isAssignableFrom(authentication);}
}
- 定义SecurityConfig配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.cors().disable();http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);http.authorizeHttpRequests().anyRequest().permitAll();http.logout().logoutSuccessHandler(logoutSuccessHandler());// 配置邮箱登录EmailAuthenticationFilter emailAuthenticationFilter = new EmailAuthenticationFilter(new AntPathRequestMatcher("/login/email", "POST"));emailAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());emailAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());emailAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler());http.addFilterBefore(emailAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);http.authenticationProvider(new EmailAuthenticationProvider());}@Beanpublic AuthenticationSuccessHandler authenticationSuccessHandler() {return (request, response, authentication) -> {// 1.生成TokenString token = UUID.randomUUID().toString();// 2.将Token和用户信息存入redisstringRedisTemplate.opsForValue().set(AuthConstants.TOKEN_PREFIX + token, JSON.toJSONString(authentication.getPrincipal()), AuthConstants.TOKEN_DURATION);// 3.返回Tokenresponse.setContentType(ResponseConstants.APPLICATION_JSON);PrintWriter writer = response.getWriter();writer.write(JSON.toJSONString(Result.success(token)));writer.flush();writer.close();};}@Beanpublic AuthenticationFailureHandler authenticationFailureHandler() {return (request, response, exception) -> {response.setContentType(ResponseConstants.APPLICATION_JSON);PrintWriter writer = response.getWriter();writer.write(JSON.toJSONString(Result.fail(exception.getMessage())));writer.flush();writer.close();};}@Beanpublic LogoutSuccessHandler logoutSuccessHandler() {return (request, response, authentication) -> {String authorization = request.getHeader(AuthConstants.AUTHORIZATION);authorization = authorization.replace(AuthConstants.BEARER, "");stringRedisTemplate.delete(AuthConstants.TOKEN_PREFIX + authorization);PrintWriter writer = response.getWriter();writer.write(JSON.toJSONString(Result.success()));writer.flush();writer.close();};}
}相关文章:
SpringSecurity自定义登录方式
自定义登录: 定义Token定义Filter定义Provider配置类中定义登录的接口 自定义AuthenticationToken public class EmailAuthenticationToken extends UsernamePasswordAuthenticationToken{public EmailAuthenticationToken(Object principal, Object credentials) …...
黑神话悟空是什么游戏 黑神话悟空配置要求 黑神话悟空好玩吗值得买吗 黑神话悟空苹果电脑可以玩吗
《黑神话:悟空》的类型定义是一款单机动作角色扮演游戏,但实际体验后会发现,游戏在很多设计上采用了「魂like」作品的常见元素。根据个人上手试玩,《黑神话:悟空》的推进节奏比较接近魂类游戏,Boss战也更像…...
深入浅出消息队列----【延迟消息的实现原理】
深入浅出消息队列----【延迟消息的实现原理】 粗说 RocketMQ 的设计细说 RocketMQ 的设计这样实现是否有什么问题? 本文仅是文章笔记,整理了原文章中重要的知识点、记录了个人的看法 文章来源:编程导航-鱼皮【yes哥深入浅出消息队列专栏】 粗…...
npm提示 certificate has expired 证书已过期 已解决
在用npm新建项目时,突然发现报错提示 : certificate has expired 证书已过期 了解一下,在网络通信中,HTTPS 是一种通过 SSL/TLS 加密的安全 HTTP 通信协议。证书在 HTTPS 中扮演着至关重要的角色,用于验证服务器身份并加密数据传输…...
KEIL如何封装文件成lib
一、为什么要封装文件成LIB 提高编译效率 如果一份文件已经在整个工程中发挥出了我们期待的作用,现在想要将其封装成库,则可以在已经成型的工程文件中将不需要编译的文件从工程全部移出掉,只留下我们需要封装的文件,这样就可以提…...
【python】OpenCV—Faster Video File FPS
文章目录 1、需求描述2、正常方法 cv2.read3、加速方法 imutils.video.FileVideoStream4、涉及到的核心库函数4.1、imutils.video.FPS4.2、imutils.video.FileVideoStream 5、参考 1、需求描述 使用线程和队列数据结构将视频文件的 FPS 速率提高 ! 我们的目标是将…...
JavaScript变量的类型转换
类型转换分为两种:显示类型转换、隐式类型转换 1.显示类型转换 String()Number()Boolean()toString()parseInt(string)parseFloat(string)2.隐式类型转换 (1)isNaN () 判断指定的参数是否为 NaN(非数字类型),返回结果为 Boolean 类型。也就是说:任何不能被转换为数值的…...
如何申请免费SSL证书以消除访问网站显示连接不安全提醒
在当今互联网时代,网络安全已成为一个不可忽视的问题。当用户浏览一些网站时,有时会看到浏览器地址栏出现“不安全”的提示,这意味着该网站没有安装SSL证书,数据传输可能存在风险。那么,如何消除这种不安全提醒&#x…...
关于P2P(点对点)
P2P 是一种客户端与客户端之间,点对点连接的技术,在早前的客户端都是公网IP,没有NAT的情况下,P2P是较为容易实现的。 但现在的P2P,实现上面会略微有一些复杂:需要采取UDP打洞的技术,但UDP打出来…...
前端怎么本地起一个服务查看本地文件
1.安装拓展 安装 Live Server拓展 2.创建一个html文件 3.在html文件中右键选择 Open with Live Server 4.浏览器打开运行的地址,并去除路径,例如:http://127.0.0.1:5500/...
建造者模式(Builder Pattern)
建造者模式(Builder Pattern)是一种创建型设计模式,它主要用于将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。这种设计模式的核心思想是将一个复杂对象的构建分解成多个相对简单的步骤,并…...
【MySQL】索引 【下】{聚簇索引VS非聚簇索引/创建主键索引/全文索引的创建/索引创建原则}
文章目录 1.聚簇索引 VS 非聚簇索引经典问题 2.索引操作创建主键索引唯一索引的创建普通索引的创建全文索引的创建查询索引删除索引索引创建原则 1.聚簇索引 VS 非聚簇索引 之前介绍的将所有的数据都放在叶子节点的这种存储引擎对应的就是 InnoDB 默认存储表数据的存储结构。 …...
论文快过(图像配准|Coarse_LoFTR_TRT)|适用于移动端的LoFTR算法的改进分析 1060显卡上45fps
项目地址:https://github.com/Kolkir/Coarse_LoFTR_TRT 创建时间:2022年 相关训练数据:BlendedMVS LoFTR [19]是一种有效的深度学习方法,可以在图像对上寻找合适的局部特征匹配。本文报道了该方法在低计算性能和有限内存条件下的…...
免费发送邮件两种接口方式:SMTP和邮件API
SMTP与邮件API在处理大批量邮件发送时,哪个更稳定? 在现代信息化的社会中,邮件已成为不可或缺的沟通工具。无论是个人还是企业,发送邮件都是日常工作的一部分。AokSend将详细介绍两种常用的免费发送邮件接口方式:SMTP…...
大模型日报 2024-07-30
大模型日报 2024-07-30 大模型资讯 开源AI性能逼近专有领袖,最新基准测试揭示 摘要: Galileo最新的幻觉指数显示,开源AI模型的性能正在迅速逼近专有巨头。这一发现表明,开源AI在技术进步和性能提升方面取得了显著进展,缩小了与专有…...
docker 构建 mongodb
最近需要在虚拟机上构建搭建mongo的docker容器,搞了半天老有错,归其原因,是因为现在最新的mango镜像的启动方式发生了变化,故此现在好多帖子,就是错的。 ok,话不多说: # 拉取最新镜像…...
LeetCode每日练习 | 二分查找 | 数组 |Java | 图解算法
🙋大家好!我是毛毛张! 🌈个人首页: 神马都会亿点点的毛毛张 📌 你真的刷明白了二分查找吗⁉️记得看毛毛张每个题目中写的【注意细节】⚠️ 文章目录 0.前言🍁1.[704. 二分查找🍍](https://l…...
2024年获客新渠道,大数据爬虫获客:技术实现精准抓取数据资源
**2024年获客新渠道:大数据爬虫获客及技术实现精准抓取数据资源** ### 一、大数据爬虫获客概述 在2024年,随着大数据技术的不断发展和互联网的普及,大数据爬虫获客已经成为企业获取客户信息、实现精准营销的重要渠道。爬虫技术通过自动化程…...
滑模变结构控制仿真实例(s-function代码详解)
目录 一、建立系统数学模型二、控制器设计1. 设计滑模面(切换面)2.设计控制器 u3. 稳定性证明 三、 Matlab 仿真1. s-function 模型2. 主要代码3. 仿真结果(采用符号函数sign(s))4. 仿真结果(采用饱和函数sat(s)) 一、建立系统数学模型 { x ˙ 1 x 2 x ˙ 2 x 3 x ˙ 3 x 1 …...
MySQL处理引擎
MySQL中的数据用各种不同的技术存储在文件(或者内存)中。这些技术中的每一种都 使用不同的存储机制、索引技巧、锁定水平并且最终提供广泛的、不同的功能和能力。通过 选择不同的技术,能够获得额外的速度或者功能,从而改善应用的整体性能。 这些不同的技…...
日语AI面试高效通关秘籍:专业解读与青柚面试智能助攻
在如今就业市场竞争日益激烈的背景下,越来越多的求职者将目光投向了日本及中日双语岗位。但是,一场日语面试往往让许多人感到步履维艰。你是否也曾因为面试官抛出的“刁钻问题”而心生畏惧?面对生疏的日语交流环境,即便提前恶补了…...
微软PowerBI考试 PL300-选择 Power BI 模型框架【附练习数据】
微软PowerBI考试 PL300-选择 Power BI 模型框架 20 多年来,Microsoft 持续对企业商业智能 (BI) 进行大量投资。 Azure Analysis Services (AAS) 和 SQL Server Analysis Services (SSAS) 基于无数企业使用的成熟的 BI 数据建模技术。 同样的技术也是 Power BI 数据…...
【JVM】- 内存结构
引言 JVM:Java Virtual Machine 定义:Java虚拟机,Java二进制字节码的运行环境好处: 一次编写,到处运行自动内存管理,垃圾回收的功能数组下标越界检查(会抛异常,不会覆盖到其他代码…...
解锁数据库简洁之道:FastAPI与SQLModel实战指南
在构建现代Web应用程序时,与数据库的交互无疑是核心环节。虽然传统的数据库操作方式(如直接编写SQL语句与psycopg2交互)赋予了我们精细的控制权,但在面对日益复杂的业务逻辑和快速迭代的需求时,这种方式的开发效率和可…...
微信小程序 - 手机震动
一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注:文档 https://developers.weixin.qq…...
相机从app启动流程
一、流程框架图 二、具体流程分析 1、得到cameralist和对应的静态信息 目录如下: 重点代码分析: 启动相机前,先要通过getCameraIdList获取camera的个数以及id,然后可以通过getCameraCharacteristics获取对应id camera的capabilities(静态信息)进行一些openCamera前的…...
鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/
使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题:docker pull 失败 网络不同,需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...
[Java恶补day16] 238.除自身以外数组的乘积
给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法,且在 O(n) 时间复杂度…...
GC1808高性能24位立体声音频ADC芯片解析
1. 芯片概述 GC1808是一款24位立体声音频模数转换器(ADC),支持8kHz~96kHz采样率,集成Δ-Σ调制器、数字抗混叠滤波器和高通滤波器,适用于高保真音频采集场景。 2. 核心特性 高精度:24位分辨率,…...
Selenium常用函数介绍
目录 一,元素定位 1.1 cssSeector 1.2 xpath 二,操作测试对象 三,窗口 3.1 案例 3.2 窗口切换 3.3 窗口大小 3.4 屏幕截图 3.5 关闭窗口 四,弹窗 五,等待 六,导航 七,文件上传 …...
