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

spring security 中的异常

一、简介

Spring Security 中异常主要分为两大类:

1、AuthenticationException: 认证异常

2、AccessDeniedException:  授权异常

  • AuthenticationEntryPoint 该类用来统一处理  AuthenticationException 异常

  • AccessDeniedHandler 该类用来统一处理  AccessDeniedException 异常

我们只要实现并配置这两个异常处理类即可实现对 Spring Security 认证授权相关的异常进行统一的自定义处理。

二、AuthenticationException 认证异常

异常介绍:

org.springframework.security.authentication.AccountStatusException  账号相关异常,抽象类,下面有三个实现类

        org.springframework.security.authentication.AccountExpiredException   账号过期异常

        org.springframework.security.authentication.CredentialsExpiredException 凭证过期(密码过期)

        org.springframework.security.authentication.DisabledException  账号禁用异常

        org.springframework.security.authentication.LockedException    账号已锁定异常

        

        

    

2.1 认证异常常用处理

    @Beanpublic LoginFilter loginVerifyImgFilter() throws Exception {LoginFilter filter = new LoginFilter();filter.setUsernameParameter("loginId");filter.setPasswordParameter("pwd");filter.setFilterProcessesUrl("/login.do");// 成功的响应filter.setAuthenticationSuccessHandler((req,resp,auth) -> {Map<String,Object> resMap = new HashMap<>();resMap.put("code","0000");resMap.put("msg","登录成功!");resMap.put("data",auth);WebRespUtils.writeJson(resp,resMap);});//登录失败的处理filter.setAuthenticationFailureHandler((req,resp,ex) -> {Map<String,Object> resMap = new HashMap<>();String errMsg = "登录失败";resMap.put("code","5001");if (ex instanceof LockedException) {errMsg = "账户被锁定,请联系管理员!";} else if (ex instanceof CredentialsExpiredException) {errMsg = "密码过期,请联系管理员!";} else if (ex instanceof AccountExpiredException) {errMsg = "账户过期,请联系管理员!";} else if (ex instanceof DisabledException) {errMsg = "账户被禁用,请联系管理员!";} else if (ex instanceof BadCredentialsException) {errMsg = "用户名或者密码输入错误,请重新输入!";}resMap.put("msg",errMsg);WebRespUtils.writeJson(resp,resMap);});// 指定自己的authenticationmanagerfilter.setAuthenticationManager(authenticationManagerBean());return filter;}

三、AccessDeniedException 授权异常

   授权异常 AccessDeniedException,授权异常的实现类比较少,因为授权失败的可能原因比较少,主要是在用户在访问受保护资源时被拒绝而抛出的异常

3.1 401 未授权状态

    HTTP 401 错误 - 未授权(Unauthorized) 一般来说该错误消息表明您首先需要登录(输入有效的用户名和密码)。如果你刚刚输入这些信息,立刻就看到一个 401 错误,就意味着,无论出于何种原因您的用户名和密码其中之一或两者都无效(输入有误,用户名暂时停用,账户被锁定,凭证失效等) 。总之就是认证失败了。其实正好对应我们上面的 AuthenticationException 。

3.2 403 被拒绝状态

    HTTP 403 错误 - 被禁止(Forbidden) 出现该错误表明您在访问受限资源时没有得到许可。服务器理解了本次请求但是拒绝执行该任务,该请求不该重发给服务器。并且服务器想让客户端知道为什么没有权限访问特定的资源,服务器应该在返回的信息中描述拒绝的理由。一般实践中我们会比较模糊的表明原因。该错误对应了我们上面的 AccessDeniedException 。

四、代码处理异常

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


/*
* 自定义认证异常处理
*/
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {Map<String,Object> resMap = new HashMap<>();String errMsg = authException.getMessage();resMap.put("code","5001");resMap.put("msg",errMsg);WebRespUtils.writeJson(response,resMap);}
}/*
* 自定义授权异常处理
*/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {response.setStatus(403);Map<String,Object> resMap = new HashMap<>();String errMsg = authException.getMessage();resMap.put("code","403");resMap.put("msg",errMsg);WebRespUtils.writeJson(response,resMap);}
}

4.2  SecurityConfig 中进行配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().......and().exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler).and()......}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【Linux系统编程】TCP实现--socket
  • 数学建模笔记——熵权法(客观赋权法)
  • 【卷起来】VUE3.0教程-05-侦听器
  • 南通网站建设手机版网页
  • HTML5好看的花店商城源码3
  • MySQL—死锁
  • 内网穿透的应用-本地化部署Elasticsearch平替工具OpenObserve并实现无公网IP远程分析数据
  • xilinx通用RAM或者FIFO设计
  • 直播相关01-录制麦克风声音,QT上 .pro 将 linux,mac和windows上配置为三种可以共享,
  • 【阿雄不会写代码】全国职业院校技能大赛GZ036第九套
  • 前端开发的单例设计模式
  • 内网穿透的应用-Deepin系统安装x11vnc实现任意设备无公网IP远程连接Deepin桌面
  • ITK-高斯滤波
  • 【数据结构与算法】——学习笔记
  • liunx io模型多路复用
  • 实现windows 窗体的自己画,网上摘抄的,学习了
  • (三)从jvm层面了解线程的启动和停止
  • 【EOS】Cleos基础
  • 【附node操作实例】redis简明入门系列—字符串类型
  • Cumulo 的 ClojureScript 模块已经成型
  • download使用浅析
  • ERLANG 网工修炼笔记 ---- UDP
  • magento2项目上线注意事项
  • maven工程打包jar以及java jar命令的classpath使用
  • node-sass 安装卡在 node scripts/install.js 解决办法
  • Spring声明式事务管理之一:五大属性分析
  • thinkphp5.1 easywechat4 微信第三方开放平台
  • 从@property说起(二)当我们写下@property (nonatomic, weak) id obj时,我们究竟写了什么...
  • 番外篇1:在Windows环境下安装JDK
  • 分布式任务队列Celery
  • 分类模型——Logistics Regression
  • 基于 Ueditor 的现代化编辑器 Neditor 1.5.4 发布
  • 技术发展面试
  • 容器服务kubernetes弹性伸缩高级用法
  • 详解NodeJs流之一
  • 赢得Docker挑战最佳实践
  • 用Visual Studio开发以太坊智能合约
  • 用简单代码看卷积组块发展
  • const的用法,特别是用在函数前面与后面的区别
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • 仓管云——企业云erp功能有哪些?
  • ​queue --- 一个同步的队列类​
  • #LLM入门|Prompt#2.3_对查询任务进行分类|意图分析_Classification
  • #调用传感器数据_Flink使用函数之监控传感器温度上升提醒
  • #考研#计算机文化知识1(局域网及网络互联)
  • #微信小程序:微信小程序常见的配置传旨
  • #我与Java虚拟机的故事#连载10: 如何在阿里、腾讯、百度、及字节跳动等公司面试中脱颖而出...
  • (1)(1.13) SiK无线电高级配置(六)
  • (70min)字节暑假实习二面(已挂)
  • (C语言)逆序输出字符串
  • (STM32笔记)九、RCC时钟树与时钟 第二部分
  • (附源码)springboot家庭装修管理系统 毕业设计 613205
  • (紀錄)[ASP.NET MVC][jQuery]-2 純手工打造屬於自己的 jQuery GridView (含完整程式碼下載)...
  • (介绍与使用)物联网NodeMCUESP8266(ESP-12F)连接新版onenet mqtt协议实现上传数据(温湿度)和下发指令(控制LED灯)
  • (免费领源码)python#django#mysql校园校园宿舍管理系统84831-计算机毕业设计项目选题推荐