怎么写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

相关文章

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

springboot将lib和jar分离的操作方法

《springboot将lib和jar分离的操作方法》本文介绍了如何通过优化pom.xml配置来减小SpringBoot项目的jar包大小,主要通过使用spring-boot-maven-plugin... 遇到一个问题,就是每次maven package或者maven install后target中的ja

Java中八大包装类举例详解(通俗易懂)

《Java中八大包装类举例详解(通俗易懂)》:本文主要介绍Java中的包装类,包括它们的作用、特点、用途以及如何进行装箱和拆箱,包装类还提供了许多实用方法,如转换、获取基本类型值、比较和类型检测,... 目录一、包装类(Wrapper Class)1、简要介绍2、包装类特点3、包装类用途二、装箱和拆箱1、装

如何利用Java获取当天的开始和结束时间

《如何利用Java获取当天的开始和结束时间》:本文主要介绍如何使用Java8的LocalDate和LocalDateTime类获取指定日期的开始和结束时间,展示了如何通过这些类进行日期和时间的处... 目录前言1. Java日期时间API概述2. 获取当天的开始和结束时间代码解析运行结果3. 总结前言在J

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动