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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

Security OAuth2 单点登录流程

单点登录(英语:Single sign-on,缩写为 SSO),又译为单一签入,一种对于许多相互关连,但是又是各自独立的软件系统,提供访问控制的属性。当拥有这项属性时,当用户登录时,就可以获取所有系统的访问权限,不用对每个单一系统都逐一登录。这项功能通常是以轻型目录访问协议(LDAP)来实现,在服务器上会将用户信息存储到LDAP数据库中。相同的,单一注销(single sign-off)就是指

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

AI绘图怎么变现?想做点副业的小白必看!

在科技飞速发展的今天,AI绘图作为一种新兴技术,不仅改变了艺术创作的方式,也为创作者提供了多种变现途径。本文将详细探讨几种常见的AI绘图变现方式,帮助创作者更好地利用这一技术实现经济收益。 更多实操教程和AI绘画工具,可以扫描下方,免费获取 定制服务:个性化的创意商机 个性化定制 AI绘图技术能够根据用户需求生成个性化的头像、壁纸、插画等作品。例如,姓氏头像在电商平台上非常受欢迎,

W外链微信推广短连接怎么做?

制作微信推广链接的难点分析 一、内容创作难度 制作微信推广链接时,首先需要创作有吸引力的内容。这不仅要求内容本身有趣、有价值,还要能够激起人们的分享欲望。对于许多企业和个人来说,尤其是那些缺乏创意和写作能力的人来说,这是制作微信推广链接的一大难点。 二、精准定位难度 微信用户群体庞大,不同用户的需求和兴趣各异。因此,制作推广链接时需要精准定位目标受众,以便更有效地吸引他们点击并分享链接