怎么写spring security的账号密码成功失败处理器并且加一个验证码过滤器

本文主要是介绍怎么写spring security的账号密码成功失败处理器并且加一个验证码过滤器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

spring security他是自带一个页面的,如果我们没有页面的话,他会进行一个账号密码的校验,成功就会走成功的处理器,失败就会走失败的处理器

成功处理器

package com.lzy.security;import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Componentpublic class LoginSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {// 将响应的内容类型设置为JSONresponse.setContentType("application/json;charset=utf-8");// 获取响应的输出流ServletOutputStream out = response.getOutputStream();//生成JWT,并且放置到请求头// 创建一个包含异常消息的Result对象Result result = Result.success("成功");// 将Result对象转换为JSON字符串,并写入输出流out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));// 刷新输出流out.flush();// 关闭输出流out.close();}}

失败处理器

package com.lzy.security;import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {// 当身份验证失败时调用此方法@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {// 将响应的内容类型设置为JSONresponse.setContentType("application/json;charset=utf-8");// 获取响应的输出流ServletOutputStream out = response.getOutputStream();// 创建一个包含异常消息的Result对象Result result = Result.fail(exception.getMessage());// 将Result对象转换为JSON字符串,并写入输出流out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));// 刷新输出流out.flush();// 关闭输出流out.close();}
}

怎么调用他们

package com.lzy.config;import com.lzy.security.CaptchaFilter;
import com.lzy.security.LoginFailureHandler;
import com.lzy.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredLoginFailureHandler loginFailureHandler;@AutowiredLoginSuccessHandler loginSuccessHandler;@AutowiredCaptchaFilter captchaFilter;private static final String[] URL_WHITELIST = {"/login","/logout","/captcha","/favicon.ico", // 防止 favicon 请求被拦截};protected void configure(HttpSecurity http) throws Exception {//跨域配置http.cors().and().csrf().disable()//登录配置.formLogin().successHandler(loginSuccessHandler).failureHandler(loginFailureHandler)//禁用session.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//配置拦截规则.and().authorizeRequests()//白名单.antMatchers(URL_WHITELIST).permitAll()//其他请求都需要认证.anyRequest().authenticated()//异常处理器//配置自定义的过滤器.and().addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);}}

因为spring security是不带验证码过滤器的,所以得我们自己写,并且要写在账号密码过滤器前,失败就走失败处理器

验证码过滤器

package com.lzy.security;import com.lzy.common.exception.CaptureException;
import com.lzy.util.Constants;
import com.lzy.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Component
public class CaptchaFilter extends OncePerRequestFilter {@AutowiredRedisUtil redisUtil;@AutowiredLoginFailureHandler loginFailureHandler;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {//判断是不是登录请求String url = request.getRequestURI();if (url.equals("/login") && request.getMethod().equals("POST")) {//如果是登录请求,判断验证码是否为空try {//验证验证码voildCaptcha(request, response, filterChain);} catch (CaptureException e) {//交给登录失败处理器loginFailureHandler.onAuthenticationFailure(request, response, e);}}filterChain.doFilter(request, response);}private void voildCaptcha(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {String captcha = request.getParameter("code");String key = request.getParameter("token");//判断验证码是否为空if (captcha.isBlank() || key.isBlank()) {throw new CaptureException("验证码不能为空");}//判断验证码是否正确if (!redisUtil.hget(Constants.CAPTURE, key).equals(captcha)) {throw new CaptureException("验证码错误");}//删除验证码redisUtil.hdel(Constants.CAPTURE, key);}}

也是在刚才的securitycofig下面调用,代码就是刚才那个

这篇关于怎么写spring security的账号密码成功失败处理器并且加一个验证码过滤器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.