怎么写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 缓存在项目中的使用详解

《Spring缓存在项目中的使用详解》Spring缓存机制,Cache接口为缓存的组件规范定义,包扩缓存的各种操作(添加缓存、删除缓存、修改缓存等),本文给大家介绍Spring缓存在项目中的使用... 目录1.Spring 缓存机制介绍2.Spring 缓存用到的概念Ⅰ.两个接口Ⅱ.三个注解(方法层次)Ⅲ.

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp

Spring Cache注解@Cacheable的九个属性详解

《SpringCache注解@Cacheable的九个属性详解》在@Cacheable注解的使用中,共有9个属性供我们来使用,这9个属性分别是:value、cacheNames、key、key... 目录1.value/cacheNames 属性2.key属性3.keyGeneratjavascriptor

redis在spring boot中异常退出的问题解决方案

《redis在springboot中异常退出的问题解决方案》:本文主要介绍redis在springboot中异常退出的问题解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴... 目录问题:解决 问题根源️ 解决方案1. 异步处理 + 提前ACK(关键步骤)2. 调整Redis消费者组

一文教你Java如何快速构建项目骨架

《一文教你Java如何快速构建项目骨架》在Java项目开发过程中,构建项目骨架是一项繁琐但又基础重要的工作,Java领域有许多代码生成工具可以帮助我们快速完成这一任务,下面就跟随小编一起来了解下... 目录一、代码生成工具概述常用 Java 代码生成工具简介代码生成工具的优势二、使用 MyBATis Gen

springboot项目redis缓存异常实战案例详解(提供解决方案)

《springboot项目redis缓存异常实战案例详解(提供解决方案)》redis基本上是高并发场景上会用到的一个高性能的key-value数据库,属于nosql类型,一般用作于缓存,一般是结合数据... 目录缓存异常实践案例缓存穿透问题缓存击穿问题(其中也解决了穿透问题)完整代码缓存异常实践案例Red

SpringCloud整合MQ实现消息总线服务方式

《SpringCloud整合MQ实现消息总线服务方式》:本文主要介绍SpringCloud整合MQ实现消息总线服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、背景介绍二、方案实践三、升级版总结一、背景介绍每当修改配置文件内容,如果需要客户端也同步更新,

java中XML的使用全过程

《java中XML的使用全过程》:本文主要介绍java中XML的使用全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录什么是XML特点XML作用XML的编写语法基本语法特殊字符编写约束XML的书写格式DTD文档schema文档解析XML的方法​​DOM解析XM

Java 的 Condition 接口与等待通知机制详解

《Java的Condition接口与等待通知机制详解》在Java并发编程里,实现线程间的协作与同步是极为关键的任务,本文将深入探究Condition接口及其背后的等待通知机制,感兴趣的朋友一起看... 目录一、引言二、Condition 接口概述2.1 基本概念2.2 与 Object 类等待通知方法的区别

SpringBoot项目中Redis存储Session对象序列化处理

《SpringBoot项目中Redis存储Session对象序列化处理》在SpringBoot项目中使用Redis存储Session时,对象的序列化和反序列化是关键步骤,下面我们就来讲讲如何在Spri... 目录一、为什么需要序列化处理二、Spring Boot 集成 Redis 存储 Session2.1