一文搞定 Spring Security 异常处理机制!

Springboot +spring security,自定义认证和授权异常处理器 阅读详情

今天来和小伙伴们聊一聊 Spring Security 中的异常处理机制。

在 Spring Security 的过滤器链中,ExceptionTranslationFilter 过滤器专门用来处理异常,在 ExceptionTranslationFilter 中,我们可以看到,异常被分为了两大类:认证异常和授权异常,两种异常分别由不同的回调函数来处理,今天就来和大家分享一下这里的条条框框。

1.异常分类

Spring Security 中的异常可以分为两大类,一种是认证异常,一种是授权异常。

认证异常就是 AuthenticationException,它有众多的实现类:

可以看到,这里的异常实现类还是蛮多的,都是都是认证相关的异常,也就是登录失败的异常。

resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
RespBean respBean = RespBean.error(e.getMessage());
if (e instanceof LockedException) {
    respBean.setMsg("账户被锁定,请联系管理员!");
} else if (e instanceof CredentialsExpiredException) {
    respBean.setMsg("密码过期,请联系管理员!");
} else if (e instanceof AccountExpiredException) {
    respBean.setMsg("账户过期,请联系管理员!");
} else if (e instanceof DisabledException) {
    respBean.setMsg("账户被禁用,请联系管理员!");
} else if (e instanceof BadCredentialsException) {
    respBean.setMsg("用户名或者密码输入错误,请重新输入!");
}
out.write(new ObjectMapper().writeValueAsString(respBean));
out.flush();
out.close();
复制代码

另一类就是授权异常 AccessDeniedException,授权异常的实现类比较少,因为授权失败的可能原因比较少。

2.ExceptionTranslationFilter

ExceptionTranslationFilter 是 Spring Security 中专门负责处理异常的过滤器,默认情况下,这个过滤器已经被自动加载到过滤器链中。

有的小伙伴可能不清楚是怎么被加载的,我这里和大家稍微说一下。

当我们使用 Spring Security 的时候,如果需要自定义实现逻辑,都是继承自 WebSecurityConfigurerAdapter 进行扩展,WebSecurityConfigurerAdapter 中本身就进行了一部分的初始化操作,我们来看下它里边 HttpSecurity 的初始化过程:

protected final HttpSecurity getHttp() throws Exception {
    if (http != null) {
        return http;
    }
    AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
    localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
    AuthenticationManager authenticationManager = authenticationManager();
    authenticationBuilder.parentAuthenticationManager(authenticationManager);
    Map<Class<?>, Object> sharedObjects = createSharedObjects();
    http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
            sharedObjects);
    if (!disableDefaults) {
        http
            .csrf().and()
            .addFilter(new WebAsyncManagerIntegrationFilter())
            .exceptionHandling().and()
            .headers().and()
            .sessionManagement().and()
            .securityContext().and()
            .requestCache().and()
            .anonymous().and()
            .servletApi().and()
            .apply(new DefaultLoginPageConfigurer<>()).and()
            .logout();
        ClassLoader classLoader = this.context.getClassLoader();
        List<AbstractHttpConfigurer> defaultHttpConfigurers =
                SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);
        for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
            http.apply(configurer);
        }
    }
    configure(http);
    return http;
}
复制代码

可以看到,在 getHttp 方法的最后,调用了 configure(http);,我们在使用 Spring Security 时,自定义配置类继承自 WebSecurityConfigurerAdapter 并重写的 configure(HttpSecurity http) 方法就是在这里调用的,换句话说,当我们去配置 HttpSecurity 时,其实它已经完成了一波初始化了。

在默认的 HttpSecurity 初始化的过程中,调用了 exceptionHandling 方法,这个方法会将 ExceptionHandlingConfigurer 配置进来,最终调用 ExceptionHandlingConfigurer#configure 方法将 ExceptionTranslationFilter 添加到 Spring Security 过滤器链中。

我们来看下 ExceptionHandlingConfigurer#configure 方法源码:

@Override
public void configure(H http) {
    AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(http);
    ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
            entryPoint, getRequestCache(http));
    AccessDeniedHandler deniedHandler = getAccessDeniedHandler(http);
    exceptionTranslationFilter.setAccessDeniedHandler(deniedHandler);
    exceptionTranslationFilter = postProcess(exceptionTranslationFilter);
    http.addFilter(exceptionTranslationFilter);
}
复制代码

可以看到,这里构造了两个对象传入到 ExceptionTranslationFilter 中:

  • AuthenticationEntryPoint 这个用来处理认证异常。
  • AccessDeniedHandler 这个用来处理授权异常。

具体的处理逻辑则在 ExceptionTranslationFilter 中,我们来看一下:

public class ExceptionTranslationFilter extends GenericFilterBean {
    public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint,
            RequestCache requestCache) {
        this.authenticationEntryPoint = authenticationEntryPoint;
        this.requestCache = requestCache;
    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            chain.doFilter(request, response);
        }
        catch (IOException ex) {
            throw ex;
        }
        catch (Exception ex) {
            Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
            RuntimeException ase = (AuthenticationException) throwableAnalyzer
                    .getFirstThrowableOfType(AuthenticationException.class, causeChain);
            if (ase == null) {
                ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(
                        AccessDeniedException.class, causeChain);
            }
            if (ase != null) {
                if (response.isCommitted()) {
                    throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed.", ex);
                }
                handleSpringSecurityException(request, response, chain, ase);
            }
            else {
                if (ex instanceof ServletException) {
                    throw (ServletException) ex;
                }
                else if (ex instanceof RuntimeException) {
                    throw (RuntimeException) ex;
                }
                throw new RuntimeException(ex);
            }
        }
    }
    private void handleSpringSecurityException(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain, RuntimeException exception)
            throws IOException, ServletException {
        if (exception instanceof AuthenticationException) {
            sendStartAuthentication(request, response, chain,
                    (AuthenticationException) exception);
        }
        else if (exception instanceof AccessDeniedException) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authenticationTrustResolver.isAnonymous(authentication) || authenticationTrustResolver.isRememberMe(authentication)) {
                sendStartAuthentication(
                        request,
                        response,
                        chain,
                        new InsufficientAuthenticationException(
                            messages.getMessage(
                                "ExceptionTranslationFilter.insufficientAuthentication",
                                "Full authentication is required to access this resource")));
            }
            else {
                accessDeniedHandler.handle(request, response,
                        (AccessDeniedException) exception);
            }
        }
    }
    protected void sendStartAuthentication(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain,
            AuthenticationException reason) throws ServletException, IOException {
        SecurityContextHolder.getContext().setAuthentication(null);
        requestCache.saveRequest(request, response);
        logger.debug("Calling Authentication entry point.");
        authenticationEntryPoint.commence(request, response, reason);
    }
}
复制代码

ExceptionTranslationFilter 的源码比较长,我这里列出来核心的部分和大家分析:

  1. 过滤器最核心的当然是 doFilter 方法,我们就从 doFilter 方法看起。这里的 doFilter 方法中过滤器链继续向下执行,ExceptionTranslationFilter 处于 Spring Security 过滤器链的倒数第二个,最后一个是 FilterSecurityInterceptor,FilterSecurityInterceptor 专门处理授权问题,在处理授权问题时,就会发现用户未登录、未授权等,进而抛出异常,抛出的异常,最终会被 ExceptionTranslationFilter#doFilter 方法捕获。
  2. 当捕获到异常之后,接下来通过调用 throwableAnalyzer.getFirstThrowableOfType 方法来判断是认证异常还是授权异常,判断出异常类型之后,进入到 handleSpringSecurityException 方法进行处理;如果不是 Spring Security 中的异常类型,则走 ServletException 异常类型的处理逻辑。
  3. 进入到 handleSpringSecurityException 方法之后,还是根据异常类型判断,如果是认证相关的异常,就走 sendStartAuthentication 方法,最终被 authenticationEntryPoint.commence 方法处理;如果是授权相关的异常,就走 accessDeniedHandler.handle 方法进行处理。

AuthenticationEntryPoint 的默认实现类是 LoginUrlAuthenticationEntryPoint,因此默认的认证异常处理逻辑就是 LoginUrlAuthenticationEntryPoint#commence 方法,如下:

public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    String redirectUrl = null;
    if (useForward) {
        if (forceHttps && "http".equals(request.getScheme())) {
            redirectUrl = buildHttpsRedirectUrlForRequest(request);
        }
        if (redirectUrl == null) {
            String loginForm = determineUrlToUseForThisRequest(request, response,
                    authException);
            RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);
            dispatcher.forward(request, response);
            return;
        }
    }
    else {
        redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
    }
    redirectStrategy.sendRedirect(request, response, redirectUrl);
}
复制代码

可以看到,就是重定向,重定向到登录页面(即当我们未登录就去访问一个需要登录才能访问的资源时,会自动重定向到登录页面)。

AccessDeniedHandler 的默认实现类则是 AccessDeniedHandlerImpl,所以授权异常默认是在 AccessDeniedHandlerImpl#handle 方法中处理的:

public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException,
        ServletException {
    if (!response.isCommitted()) {
        if (errorPage != null) {
            request.setAttribute(WebAttributes.ACCESS_DENIED_403,
                    accessDeniedException);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
            dispatcher.forward(request, response);
        }
        else {
            response.sendError(HttpStatus.FORBIDDEN.value(),
                HttpStatus.FORBIDDEN.getReasonPhrase());
        }
    }
}
复制代码

可以看到,这里就是服务端跳转返回 403。

3.自定义处理

前面和大家介绍了 Spring Security 中默认的处理逻辑,实际开发中,我们可以需要做一些调整,很简单,在 exceptionHandling 上进行配置即可。

首先自定义认证异常处理类和授权异常处理类:

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.getWriter().write("login failed:" + authException.getMessage());
    }
}
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(403);
        response.getWriter().write("Forbidden:" + accessDeniedException.getMessage());
    }
}
复制代码

然后在 SecurityConfig 中进行配置,如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                ...
                ...
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(myAuthenticationEntryPoint)
                .accessDeniedHandler(myAccessDeniedHandler)
                .and()
                ...
                ...
    }
}
复制代码

配置完成后,重启项目,认证异常和授权异常就会走我们自定义的逻辑了。

SpringSecurity6解决requestMatchers().permitAll()后依然执行自定义过滤器的问题 Spring容器会自动识别被注册成为Bean对象的Filter过滤器(即继承自Filter对象的类),将这个Bean对象自动注册到SpringBoot的过滤器链中。如果你的过滤器类使用注解注册成为了一个Bean对象,那么他就已经加到了SpringBoot的过滤器链中,所以就算你的SpringSecurity配置中设置了permitAll,可能还会去走SpringBoot的过滤器链。 阅读详情

相关推荐

若依权限认证改造实战:从Spring Security到saToken

在Java后端项目开发中,权限认证是每一个管理后台都必须面对的核心技术环节。Spring Security作为Java生态中主流的认证与授权框架,功能全面,但配置复杂、扩展成本高,尤其在若依这类基于Spring Boot的中小规模项目中,其内置的Spring Security + JWT方案常常让开发者在过滤器链、认证管理器、权限注解中耗费大量精力。面对登录集成、会话控制、权限模型定制等需求,不少团队开始寻求轻量、开箱即用的替代方案。saToken作为一款国产开源权限认证框架,以极简的API设计、清晰的中文

weixin_34343308的博客 382

SpringSecurity异常处理源码解析

SpringSecurity异常处理源码解析 异常处理主要是由ExceptionTranslationFilter完成的,而ExceptionTranslationFilter是由ExceptionHandlingConfigurer配置的,所以我们从ExceptionHandlingConfigurer开始解析 我们首先看ExceptionHandlingConfigurer的configure(Httpsecurity security)方法: @Override public void configu

HHoao的博客 1061

Spring Security核心架构与生产级应用实战指南

在Web应用开发中,认证与授权是保障系统安全的核心机制。认证解决“你是谁”的问题,通过验证用户身份确保访问者合法;授权则解决“你能干什么”的问题,依据权限控制资源访问范围。Spring Security作为Spring生态的安全框架,通过声明式配置和过滤器链机制,将复杂的安全逻辑抽象为可定制的组件,显著提升开发效率与系统安全性。其技术价值在于提供了标准化、模块化的安全解决方案,支持从基础表单登录到OAuth 2.0第三方登录等多种认证方式,并能与MyBatis-Plus、Activiti等常用框架无缝整合。

weixin_33971977的博客 597

easyui datagrid重新加载detailview异常_一文搞定 Spring Security 异常处理机制!

松哥原创的 Spring Boot 视频教程已经杀青,感兴趣的小伙伴戳这里-->Spring Boot+Vue+微人事视频教程今天来和小伙伴们聊一聊 Spring Security 中的异常处理机制。在 Spring Security 的过滤器链中,ExceptionTranslationFilter 过滤器专门用来处理异常,在 ExceptionTranslationFilter...

weixin_39864453的博客 131

Spring Security 异常处理

org.springframework.security.authentication.BadCredentialsException: 用户名或密码错误。当我们登录的时候,如果用户名找不到,则抛出:UsernameNotFoundException,可以被拦截到LoginFailureHandler。因为UsernameNotFoundException继承自:AuthenticationException。

2012年开始工作,全栈开发老兵,目前已是一个老师,分享这么多年的心得体会 409

1.用Python写了一个进销存管理的软件~需求分析&界面设计&数据库设计&技术路线选择~

前端也打算用Python来写,查了很多的python库,大家比较推荐的是wxpython和QPython,之前接触过一点点的QT,确实非常强大,但是库比较重量级,自己写的这个东西明显配不上QT,又详细调研了一下wxpython,就是它了!

pepper_lihui的专栏 4329

easyui datagrid重新加载detailview异常_一文搞定 Spring Security 异常处理机制

今天来和小伙伴们聊一聊 Spring Security 中的异常处理机制。在 Spring Security 的过滤器链中,ExceptionTranslationFilter 过滤器专门用来处理异常,在 ExceptionTranslationFilter 中,我们可以看到,异常被分为了两大类:认证异常和授权异常,两种异常分别由不同的回调函数来处理,今天松哥就来和大家分享一下这里的条条框框。1....

weixin_39618824的博客 289

新手入门:N-CMAPSS数据集解析与实战指南

本文详细解析了N-CMAPSS数据集的结构与应用,为新手提供航空发动机故障预测的实战指南。通过Python代码示例展示数据加载、探索和特征工程技巧,帮助读者快速掌握剩余寿命(RUL)预测的关键步骤,并分享常见问题解决方案与进阶学习路径。

weixin_29056701的博客 384

68篇干货,手把手教你通关 Spring Security!

Spring Security 系列前前后后整了 68 篇文章了,是时候告一个段落了。 这两天松哥抽空把该系列的文章整理了一下,做成了一个索引,方便小伙伴们查找。 教程地址如下: http://www.javaboy.org/springsecurity http://www.itboyhub.com/springsecurity 对应的 Demo 地址如下: https://github.com/lenve/spring-security-samples https://github.com/len

江南一点雨的专栏 6576

5分钟搞定单细胞marker基因气泡图:scDotPlot保姆级教程(含Seurat适配)

本文提供了一份详细的scDotPlot R包使用教程,帮助用户在5分钟内完成单细胞marker基因气泡图的绘制。教程涵盖环境准备、Seurat和SingleCellExperiment对象的适配处理、进阶可视化技巧及自动化报告生成,特别适合生物信息学新手和临床研究者快速掌握这一高效的可视化工具。

weixin_29047545的博客 267

欧姆龙SYSMAC STUDIO如何与基恩士SR-1000进行EIP通信

简要介绍一下扫码枪和欧姆龙sysmac的配置

weixin_42031602的博客 4827

Spring Boot 3.x 实战:别再手动写Filter了,用Spring Security 6优雅搞定Remember-Me功能

本文详细解析了Spring Boot 3.x与Spring Security 6中Remember-Me功能的现代化实现方式,告别手动Filter的繁琐与安全隐患。通过框架级解决方案,开发者可轻松实现军事级加密、灵活存储策略和无缝集成,显著提升Web应用的安全性与用户体验。文章还涵盖了前后端分离架构的适配策略及实战案例,帮助开发者高效部署Remember-Me功能。

weixin_30654419的博客 362

在Mac上搭建本地AI工作流:Dify与DeepSeek的完美结合

本文介绍了在Mac上搭建本地AI工作流的方法,结合Dify平台和DeepSeek模型。Dify是一个开源的大语言模型应用开发平台,支持可视化AI应用开发。部署步骤包括:1)安装Homebrew和Docker;2)克隆Dify代码库;3)配置环境变量并启动服务。同时,使用Ollama工具本地部署DeepSeek模型,将其集成到Dify中创建聊天助手。通过配置模型接口和新建应用,用户可以在本地环境中实现AI对话功能。这种方案既保证了数据隐私,又提供了灵活的AI应用开发能力。

Linda的自动化测试之旅 1542

Spring Security从入门到实战:一文搞懂认证与授权

Spring Security是Spring家族的安全框架,负责认证(你是谁)和授权(你能干什么)。用户请求 --> Spring Security过滤器链 --> 你的Controller↓│ 1. 认证(你是谁)│ --> 用户名密码验证、Token验证│ 2. 授权(能干嘛)│ --> 你有没有权限访问这个接口用户登录认证(用户名密码、OAuth2、JWT)接口权限控制(RBAC角色权限)防护攻击(CSRF、XSS、会话固定)集成OAuth2/单点登录。

2603_95882547的博客 648

从光耦隔离到稳定驱动:信捷伺服与STM32的硬件设计陷阱与救赎

本文深入探讨了信捷伺服驱动器与STM32微控制器配合时的硬件设计关键问题,包括光耦隔离电路选型、电源电压选择、拨码开关设置等核心环节。针对伺服驱动器的稳定驱动需求,提供了从电路设计到抗干扰策略的完整解决方案,帮助工程师规避常见陷阱,提升工业控制系统的可靠性。

gold8的专栏 316

AHB—SRAMC项目(结构图,核心代码、Testbench架构)

文章目录一、AHB_SRAMC项目介绍1.1.AHB总线控制单元(ahb_slv_if.v)1.2.SRAM控制单元(sramc_top.v)1.3.主要的传输路径二、结构框图2.1.AHB_SRAMC结构图(重点)2.2.总线控制单元与SRAM控制单元结构图三、部分核心代码(重点理解)四、SystemVerilog Testbench架构(重点)五、目录结构 一、AHB_SRAMC项目介绍 本项...

Mr.翟的博客 3万+

springsecurity oauth2 一文搞定 Spring Security 异常拦截处理机制!

https://wangsong.blog.csdn.net/article/details/107033269

yrsg666的博客 1739

4.2 多智能体系统的严格隔离机制:防止上下文污染与隐私数据脱敏实战

本文探讨了多智能体系统中上下文信息共享带来的安全风险与解决方案。研究发现,随着Agent数量增加,上下文信息泄露概率呈指数级上升,可能导致跨Agent错误传播、隐私泄露等问题。文章提出分层隔离架构,将上下文划分为全局共享和本地私有两部分,并通过命名空间隔离、递归压缩和隐私过滤技术确保数据安全。技术实现上,建议为每个子Agent创建独立状态空间,采用原子化更新和读写锁控制避免状态竞争。隐私保护方面,结合正则匹配和命名实体识别技术进行敏感数据过滤,确保符合GDPR等法规要求。这些措施共同构建了可靠、安全且合规的

公众号:AI前沿侦探 238

双Token认证体系深度拆解:Spring Security + JWT + Redis

本文深入解析双Token认证体系,通过Spring Security和JWT实现安全高效的认证方案。 核心内容: 双Token设计原理:短效Access Token(15分钟)用于API请求,长效Refresh Token(7天)存储于Redis实现状态控制 完整认证流程:登录生成双Token、Access Token刷新、登出黑名单机制 关键技术实现: JWT结构设计与签名验证 Spring Security过滤链配置 Redis存储Refresh Token实现状态管理 RBAC权限模型集成 安全实践:

weixin_72753562的博客 2346

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Springboot3.x.x使用SpringSecurity6(一文包搞定)

Springboot3.x.x使用SpringSecurity6(一文包搞定)Spring Security 是一个强大的、高度可定制的身份验证(Authentication)和访问控制(Authorization)框架。它是 Spring 框架家族的一员,主要用于保护基于 Java 的应用程序,无论是Web应用还是非Web应用。Spring Security 在过去,Spring Security 的配置相对复杂,但是随着 Spring Boot 的出现,它提供了自动配置方案,使得集成 Spring Se

m0_64787068的博客 2380

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

上一篇: 「图解」ThreadLocal 在并发问题中的应用
下一篇: 一文搞定FastDFS的搭建和使用
Java技术那些事儿
博客等级 码龄5年 2306粉丝 2584原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址