当前位置: 首页 > news >正文

【Spring Security】AuthenticationFailureHandler 用户认证失败后处理

文章目录

    • 前言
    • 简单介绍官方默认用户认证失败后处理器
      • SimpleUrlAuthenticationFailureHandler
      • ForwardAuthenticationFailureHandler
      • ExceptionMappingAuthenticationFailureHandler
      • DelegatingAuthenticationFailureHandler
    • 自定义使用
    • SecurityConfiguration 配置


前言

AuthenticationFailureHandler 主要是做用户认证失败后调用的处理器,这里的失败一般是指用户名或密码错误。当出现错误后,该处理器就会被调用,一般在开发中,会自己实现一个处理器,用来给前端返回一些已经商量好的异常码,下面分成两大块,先简单介绍一下官方给的一些用户失败后的处理器,再介绍我们自己实现的自定义处理器。



简单介绍官方默认用户认证失败后处理器

SimpleUrlAuthenticationFailureHandler

当认证失败后,重定向到一个指定的URL。

@Override
protected void configure(HttpSecurity http) throws Exception {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowCredentials(true);http// 登录.formLogin()// 认证失败后处理器.failureHandler(authenticationFailureHandler());
}@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler();// 认证失败后重定向的URLhandler.setDefaultFailureUrl("/login?error=true");return handler;
}

ForwardAuthenticationFailureHandler

认证失败后转发到一个指定的URL。

@Override
protected void configure(HttpSecurity http) throws Exception {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowCredentials(true);http// 登录.formLogin()// 认证失败后处理器.failureHandler(authenticationFailureHandler());
}@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {// 认证失败后转发的URLreturn new ForwardAuthenticationFailureHandler("/login-error");
}

ExceptionMappingAuthenticationFailureHandler

认证失败中根据发生的异常类型映射到不同的处理逻辑或URL。

@Override
protected void configure(HttpSecurity http) throws Exception {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowCredentials(true);http// 登录.formLogin()// 认证失败后处理器.failureHandler(authenticationFailureHandler());
}@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {ExceptionMappingAuthenticationFailureHandler handler = new ExceptionMappingAuthenticationFailureHandler();// 定义异常到URL的映射Map<String, String> exceptionMappings = new HashMap<>();exceptionMappings.put(IOException.class.getName(), "/login?error=io");exceptionMappings.put(RuntimeException.class.getName(), "/login?error=runtime");// 更多映射...handler.setExceptionMappings(exceptionMappings);// 当找不到映射时默认的URLhandler.setDefaultFailureUrl("/login?error=def");return handler;
}

DelegatingAuthenticationFailureHandler

认证过程中发生的异常来委派给不同的 AuthenticationFailureHandler 实现。

@Override
protected void configure(HttpSecurity http) throws Exception {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowCredentials(true);http// 登录.formLogin()// 认证失败后处理器.failureHandler(authenticationFailureHandler());
}@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> failureHandlers = new LinkedHashMap<>();// 使用重定向failureHandlers.put(BadCredentialsException.class, new SimpleUrlAuthenticationFailureHandler("/login?error=bad_credentials"));// 使用转发failureHandlers.put(LockedException.class, new ForwardAuthenticationFailureHandler("/login-error"));// 更多映射...return new DelegatingAuthenticationFailureHandler(failureHandlers,// 默认策略new SimpleUrlAuthenticationFailureHandler("/login?error=def"));
}


自定义使用

package com.security.handler.auth;import com.alibaba.fastjson2.JSON;
import com.security.controller.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@Component
@Slf4j
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {log.info("AuthenticationFailureHandlerImpl 登录认证失败时调用 ...");/*** 设置响应状态值*/response.setStatus(402);response.setContentType("application/json");response.setCharacterEncoding("utf-8");String json = JSON.toJSONString(ResponseResult.builder().code(402).message("认证失败!").build());// JSON信息response.getWriter().println(json);}}

SecurityConfiguration 配置

package com.security.config;import com.security.handler.auth.AuthenticationFailureHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.cors.CorsConfiguration;@Configuration
@EnableWebSecurity
// 开启限制访问资源所需权限
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationTest extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowCredentials(true);http// 登录.formLogin()// 认证失败后处理器.failureHandler(authenticationFailureHandler());}@Beanpublic AuthenticationFailureHandler authenticationFailureHandler() {// 自定义的失败后的处理器return new AuthenticationFailureHandlerImpl();}
}




End


相关文章:

  • 数据特征工程 | PSO粒子群算法的特征选择原理及python代码实现
  • web component - 使用HTML Templates和Shadow DOM构建现代UI组件
  • [BUG]Datax写入数据到psql报不能序列化特殊字符
  • C# MVC +Layui侧边导航栏的收缩及展开
  • VUE——IDEA 启动前端工程VS文件启动前端工程
  • 【操作系统】虚拟存储器
  • 相比于其他流处理技术,Flink的优点在哪?
  • N 皇后 II[困难]
  • 你好!Apache Seata
  • Android--Jetpack--Paging详解
  • C#-CSC编译环境搭建
  • 千巡翼X4轻型无人机 赋能智慧矿山
  • 【 YOLOv5】目标检测 YOLOv5 开源代码项目调试与讲解实战(4)-自制数据集及训练(使用makesense标注数据集)
  • uni-app 前后端调用实例 基于Springboot 数据列表显示实现
  • Baumer工业相机堡盟工业相机如何通过NEOAPI SDK获取相机当前实时帧率(C#)
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • git 常用命令
  • HTTP请求重发
  • If…else
  • Linux编程学习笔记 | Linux多线程学习[2] - 线程的同步
  • Protobuf3语言指南
  • Redash本地开发环境搭建
  • 搞机器学习要哪些技能
  • 前端之Sass/Scss实战笔记
  • 深入浏览器事件循环的本质
  • 世界上最简单的无等待算法(getAndIncrement)
  • 学习HTTP相关知识笔记
  • 一些css基础学习笔记
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • 职业生涯 一个六年开发经验的女程序员的心声。
  • 没有任何编程基础可以直接学习python语言吗?学会后能够做什么? ...
  • $ is not function   和JQUERY 命名 冲突的解说 Jquer问题 (
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (175)FPGA门控时钟技术
  • (HAL)STM32F103C6T8——软件模拟I2C驱动0.96寸OLED屏幕
  • (NO.00004)iOS实现打砖块游戏(九):游戏中小球与反弹棒的碰撞
  • (分布式缓存)Redis哨兵
  • (规划)24届春招和25届暑假实习路线准备规划
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (企业 / 公司项目)前端使用pingyin-pro将汉字转成拼音
  • (四)Android布局类型(线性布局LinearLayout)
  • (转)关于如何学好游戏3D引擎编程的一些经验
  • (转载)VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)
  • *p++,*(p++),*++p,(*p)++区别?
  • .NET C# 操作Neo4j图数据库
  • .net core 的缓存方案
  • .Net多线程Threading相关详解
  • .NET项目中存在多个web.config文件时的加载顺序
  • :中兴通讯为何成功
  • [ CTF ] WriteUp- 2022年第三届“网鼎杯”网络安全大赛(白虎组)
  • [ SNOI 2013 ] Quare
  • []AT 指令 收发短信和GPRS上网 SIM508/548
  • [《百万宝贝》观后]To be or not to be?
  • [2024-06]-[大模型]-[Ollama] 0-相关命令
  • [ASP.NET 控件实作 Day7] 设定工具箱的控件图标