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

news2024/10/6 18:33:38

一.简介

在Spring Security中异常分为两种:

  1. AuthenticationException 认证异常
  2. AccessDeniedException 权限异常 我们先给大家演示下如何自定义异常处理器,然后再结合源码帮助大家进行分析

二.创建项目

如何创建一个SpringSecurity项目,前面文章已经有说明了,这里就不重复写了。

三.自定义异常处理器

3.1配置SecurityConfig

这里主要是authenticationEntryPoint和accessDeniedHandler配置,代码如下:

@Bean
    public SecurityFilterChain config(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .permitAll()
                .and()
                .cors()
                .configurationSource(corsConfigurationSource())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        Map<String, Object> result = new HashMap<>();
                        result.put("code", -1);
                        result.put("msg", "authenticationEntryPoint");
                        result.put("data", authException.getMessage());
                        System.out.println("调用次数");
                        writeResp(result, response);
                    }
                }).accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        Map<String, Object> result = new HashMap<>();
                        result.put("code", -1);
                        result.put("msg", "accessDeniedHandler");
                        result.put("data", accessDeniedException.getMessage());
                        writeResp(result, response);
                    }
                })
                .and()
                .csrf().disable();
        http.headers().cacheControl();
        return http.build();
    }

3.2自定义登录页面

为什么要自定义登录页面呢,因为如果我们实现了异常处理端点,security 就不会将生成登录页面的过滤器加入,我们看下源码:“authenticationEntryPoint == null)”才会添加自定义生成登录页面的过滤器。

代码如下:

 public void configure(H http) {
  AuthenticationEntryPoint authenticationEntryPoint = null;
  ExceptionHandlingConfigurer<?> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class);
  if (exceptionConf != null) {
   authenticationEntryPoint = exceptionConf.getAuthenticationEntryPoint();
  }
  if (this.loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
   this.loginPageGeneratingFilter = postProcess(this.loginPageGeneratingFilter);
   http.addFilter(this.loginPageGeneratingFilter);
   LogoutConfigurer<H> logoutConfigurer = http.getConfigurer(LogoutConfigurer.class);
   if (logoutConfigurer != null) {
    http.addFilter(this.logoutPageGeneratingFilter);
   }
  }
 }

登陆页面代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="SPRING_SECURITY_LAST_EXCEPTION"></div>
<form action="/login" method="post">
    用户名:<input name="username" type="text"><br>
    密码:<input name="password" type="password"><br>
    <button type="submit">登陆</button>
</form>
</body>
</html>

3.3配置用户信息

代码如下:

spring.security.user.password=123456
spring.security.user.roles=admin
spring.security.user.name=lglbc

3.4添加controller

代码如下:

 @RequestMapping("/user")
    @PreAuthorize("hasRole('user')")
    public String user() {
        return "hello";
    }
    @RequestMapping("/admin")
    @PreAuthorize("hasRole('admin')")
    public String admin() {
        return "admin";
    }

3.4验证

验证匿名访问user接口

http://localhost:8080/user,截图如下:
在这里插入图片描述
返回的是自定义异常,被Authentication进行处理,稍后从源码角度分析。

验证登录后访问admin接口
在这里插入图片描述
请求成功,返回接口数据 需要注意的是,如果实现了异常端点,想之前自动跳转到登录页面将不再生效,因为这些逻辑都是在默认的异常端点里面处理

3.5异常过滤器实现原理分析

上面讲到自定义异常端点的回调都是通过异常处理过滤器实现,我们现在就从这块开始看, 首先,我们还是从入口开始找:.exceptionHandling() 点击.exceptionHandling()进入到代码中,我们发现我们熟悉的ExceptionHandlingConfigurer,代码如下:

public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws Exception {
    return getOrApply(new ExceptionHandlingConfigurer<>());
   }

3.5.1init

ExceptionHandlingConfigurer没有重写,所以我们就直接看configure方法

3.5.2configure

 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);
 }
  1. 创建过滤 ExceptionTranslationFilter
  2. 获取两种异常的处理端点,如果我们配置了就会使用我们自己的,否则使用默认的 *
    在这里插入图片描述

在这里插入图片描述

  1. 将端点配置到ExceptionTranslationFilter中
  2. 将ExceptionTranslationFilter 放到IOC容器中,并且放到过滤器链中 *
    在这里插入图片描述
    加入的时候,会获取过滤器的优先级,ExceptionTranslationFilter放在了AuthorizationFilter之前,这个后面讲到为什么这么做

在这里插入图片描述
看configure方法就是为了看它到底使用什么过滤器,现在我们直接看ExceptionTranslationFilter。

3.5.3ExceptionTranslationFilter

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
   throws IOException, ServletException {
  try {
   chain.doFilter(request, response);
  }
  catch (IOException ex) {
   throw ex;
  }
  catch (Exception ex) {
   // Try to extract a SpringSecurityException from the stacktrace
   Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
   RuntimeException securityException = (AuthenticationException) this.throwableAnalyzer
     .getFirstThrowableOfType(AuthenticationException.class, causeChain);
   if (securityException == null) {
    securityException = (AccessDeniedException) this.throwableAnalyzer
      .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
   }
   if (securityException == null) {
    rethrow(ex);
   }
   if (response.isCommitted()) {
    throw new ServletException("Unable to handle the Spring Security Exception "
      + "because the response is already committed.", ex);
   }
   handleSpringSecurityException(request, response, chain, securityException);
  }
 }

在doFilter方法中,异常过滤器直接调用了下个过滤器,并没有做什么

  1. 捕获执行下个过滤器的异常
  2. 将异常丢给handleSpringSecurityException()方法进行处理

handleSpringSecurityException类的代码如下:

private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response,
   FilterChain chain, RuntimeException exception) throws IOException, ServletException {
  if (exception instanceof AuthenticationException) {
   handleAuthenticationException(request, response, chain, (AuthenticationException) exception);
  }
  else if (exception instanceof AccessDeniedException) {
   handleAccessDeniedException(request, response, chain, (AccessDeniedException) exception);
  }
 }

根据异常类型不同,分别调用不同的处理方法

handleAuthenticationException类代码如下:

private void handleAuthenticationException(HttpServletRequest request, HttpServletResponse response,
   FilterChain chain, AuthenticationException exception) throws ServletException, IOException {
  this.logger.trace("Sending to authentication entry point since authentication failed", exception);
  sendStartAuthentication(request, response, chain, exception);
 }
 
  protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
   AuthenticationException reason) throws ServletException, IOException {
  // SEC-112: Clear the SecurityContextHolder's Authentication, as the
  // existing Authentication is no longer considered valid
  SecurityContext context = SecurityContextHolder.createEmptyContext();
  SecurityContextHolder.setContext(context);
  this.requestCache.saveRequest(request, response);
  this.authenticationEntryPoint.commence(request, response, reason);
 }

这个是直接调用了this.authenticationEntryPoint.commence方法,authenticationEntryPoint讲过,如果我们配置了就使用配置的,否则使用默认的端点处理

handleAccessDeniedException类代码如下:

private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response,
   FilterChain chain, AccessDeniedException exception) throws ServletException, IOException {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication);
  if (isAnonymous || this.authenticationTrustResolver.isRememberMe(authentication)) {
   sendStartAuthentication(request, response, chain,
     new InsufficientAuthenticationException(
       this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication",
         "Full authentication is required to access this resource")));
  }
  else {
   this.accessDeniedHandler.handle(request, response, exception);
  }
 }

这个处理逻辑和前面有点不同

  1. 如果未登录或者是rememberMe,则还是调用sendStartAuthentication
  2. 否则调用this.accessDeniedHandler.handle(),这个和前面的逻辑一致

四.最后用一张图总结

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/573377.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分布式锁和事务关系的细节

使用redssion在redis上以及结合自定义注解利用spring的环绕切面来实现分布式锁功能 代码示例 controller、service层 RequestMapping("insertNumber/{number}/{id}") public boolean insertNumber(PathVariable Long number,PathVariable Long id){return testSer…

rust 中protobuf生成与使用

首先创建一个项目proto 进入到这个文件夹中 创建我们的proto文件 初始化的项目结构是这个样子的 新建一个hello.proto文件内容如下 syntax "proto3";package hello;service Greeter {rpc SayHello (HelloRequest) returns (HelloReply) {} }message HelloRequest …

干货 | 师兄手把手教你如何踏上科研道路

Hello&#xff0c;大家好&#xff01; 这里是壹脑云科研圈&#xff0c;我是喵君姐姐&#xff5e; 今天&#xff0c;邀请到鲁小白&#xff0c;给大家分享一下他踏上科研道路的心路历程。 大家好&#xff0c;我是鲁小白&#xff0c;我真正进入科研的时间&#xff0c;研究生3年再…

【C++】类和对象——类的引入、类的访问限定符、类的作用域、类的实例化、类的储存、this指针的引出和特性

文章目录 1.类的引入2.类的访问限定符3.类的作用域4.类的实例化5.类的储存6.this指针6.1this指针的引出6.2this指针的特性 1.类的引入 C是在C的基础上加以扩展。 在C语言中&#xff0c;我们想要让一个类型含有多种成员变量&#xff0c;我们使用结构体&#xff1b;而在C中我们可…

Doris节点扩容及数据表

扩容和缩容 上篇文章简单讲了doris的安装&#xff0c;本章分享的是doris中fe和be节点的扩容缩容以及doris的数据表1、FE 扩容和缩容 使用 MySQL 登录客户端后&#xff0c;可以使用 sql 命令查看 FE 状态&#xff0c;目前就一台 FE mysql -h linux -P 9030 -uroot -p mysql&…

python+django乡村居民数据的可视化平台

本论文主要论述了如何使用Django框架开发一个乡村振兴数据的可视化平台 &#xff0c;本系统将严格按照软件开发流程进行各个阶段的工作&#xff0c;采用B/S架构&#xff0c;面向对象编程思想进行项目开发。在引言中&#xff0c;作者将论述乡村振兴数据的可视化平台的当前背景以…

拼多多二面,原来是我对自动化测试的理解太浅了

如果你入职一家新的公司&#xff0c;领导让你开展自动化测试&#xff0c;作为一个新人&#xff0c;你肯定会手忙脚乱&#xff0c;你会如何落地自动化测试呢&#xff1f; 01 什么是自动化 有很多人做了很长时间的自动化但却连自动化的概念都不清楚&#xff0c;这样的人也是很悲…

Android之 MVC到MVVM架构发展和封装

一 简介 1.1 软件架构发展趋势是解耦&#xff0c;即分离数据层和视图层&#xff0c;使得数据层专注于业务的数据和逻辑处理。从而提高代码的可读可编辑效率&#xff0c;提高团队协作能力&#xff0c;项目的生产能力&#xff0c;降低后期维护成本。 1.2 Android架构发展MVC -…

计算机组成原理实验四 微程序控制器实验报告

我班算是几乎最后一个做实验的班级了&#xff0c;报告参考了一些朋友提供的数据加上一些自己的主观拙见&#xff0c;本人水平有限加之制作仓促难免有错误&#xff0c;望大家批评指正。 4.1 微程序控制器实验 一、实验目的 (1) 掌握微程序控制器的组成原理。 (2) 掌握微程序的…

【蓝桥杯计算思维题】少儿编程 蓝桥杯青少组计算思维真题及详细解析第5套

少儿编程 蓝桥杯青少组计算思维真题及详细解析第5套 1、北京冬奥会经历 17( ),中国体育代表团收获的金牌数和奖牌数均创历史新高 A、年 B、月 C、天 D、小时 答案:C 考点分析:主要考查小朋友们对时事的了解,北京冬奥会总共经历了17天,所以答案C 2、下面图形的周长是…

Python系列模块之标准库json详解

感谢点赞和关注 &#xff0c;每天进步一点点&#xff01;加油&#xff01; 目录 一、Json介绍 二、JSON 函数 2.1 json.dumps 2.2 json.loads 2.3 实战案例&#xff1a;钉钉消息发送 一、Json介绍 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。它使得人们…

2023年21个最佳的Ruby测试框架

作者 | Veethee Dixit 测试人员总是在寻找最好的自动化测试框架&#xff0c;它能提供丰富的功能&#xff0c;并且语法简单、兼容性好、执行速度快。如果你选择将Ruby与Selenium结合起来进行web测试&#xff0c;那么可能需要搜索基于Ruby的测试框架进行web应用程序测试。 Ruby…

【Python】函数式编程第二弹

知识目录 一、写在前面✨二、最小公倍数三、移除数字四、总结撒花&#x1f60a; 一、写在前面✨ 大家好&#xff01;我是初心&#xff0c;希望我们一路走来能坚守初心&#xff01; 今天跟大家分享的文章是 Python函数式编程第二弹&#xff0c;再次以两个简单的例子带大家更好…

selenium UI自动化中文件上传的两种方式

前言 文件上传是自动化中很常见的一个功能&#xff0c;那么对于文件上传你又有多少了解呢&#xff1f;请往下看 1、被测产品中文件上传的功能非常普遍&#xff0c;一般情况下需要将准备好的文件放在预定的路径下&#xff0c;然后在自动化测试的脚本中&#xff0c;去预置的路径…

国内可以免费使用的GPT

一、wetab新标签页 教程&#xff1a;https://diwlwltzssn.feishu.cn/docx/MnHhdvxATomBnMxfas2cm8wWnVd 装GPT界面&#xff1a;https://microsoftedge.microsoft.com/addons/detail/wetab%E5%85%8D%E8%B4%B9chatgpt%E6%96%B0%E6%A0%87%E7%AD%BE%E9%A1%B5/bpelnogcookhocnaokfp…

TeX Live和TeX studio安装

最近想要研究一下Letex怎么写论文&#xff0c;然后就查阅资料了解了一下&#xff0c;先安装上两个软件&#xff0c;怎么用在研究研究&#xff0c;这里记录一下软件安装过程&#xff0c;方便以后查阅。 TeX Live和TeX studio安装 Latex介绍TexLive安装下载TexLive的安装包安装Te…

C++知识第三篇之继承

C继承 继承是面向对象编程的重要特征&#xff0c;是对类设计层次的复用 文章目录 C继承一.介绍1.继承定义2.继承方式3.class与struct 二.作用域1.成员变量2.成员函数 三.赋值转换1.给基类对象赋值2.给基类对象指针赋值 四.派生类的默认函数五. 其他1.友元2.静态 六.继承1.单继承…

Android车载学习笔记1——车载整体系统简介

一、汽车操作系统 汽车操作系统包括安全车载操作系统、智能驾驶操作系统和智能座舱操作系统。 1. 安全车载操作系统 安全车载操作系统主要面向经典车辆控制领域&#xff0c;如动力系统、底盘系统和车身系统等&#xff0c;该类操作系统对实时性和安全性要求极高&#xff0c;生态…

VCSA 和ESXi 6.7.0版本升级

1. VCSA升级步骤 1&#xff09;指定升级包的位置 software-packages stage --iso (如果是从vmware下载补丁&#xff0c;使用CD/DVD来映射ISO映像) 或 software-packages stage --url https://vapp-updates.vmware.com/vai-catalog/valm/vmw/8d167796-34d5-4899-be0a-6daade400…

Yolov8涨点神器:注意力机制---多头上下文集成(Context Aggregation)的广义构建模块,助力小目标检测,暴力涨点

🏆🏆🏆🏆🏆🏆Yolov8魔术师🏆🏆🏆🏆🏆🏆 ✨✨✨魔改网络、复现前沿论文,组合优化创新 🚀🚀🚀小目标、遮挡物、难样本性能提升 🍉🍉🍉定期更新不同数据集涨点情况 2.Context Aggregation介绍 论文:https://arxiv.org/abs/2106.01401 仅…