源码地址:https://github.com/jitwxs/blog_sample

文章目录

一、常见异常
二、源码分析
三、处理异常
不知道你有没有注意到,当我们登陆失败时候,Spring security 帮我们跳转到了 /login?error Url,奇怪的是不管是控制台还是网页上都没有打印错误信息。

这是因为首先 /login?error 是 Spring security 默认的失败 Url,其次如果你不手动处理这个异常,这个异常是不会被处理的。

一、常见异常

我们先来列举下一些 Spring Security 中常见的异常:

  • UsernameNotFoundException(用户不存在)
  • DisabledException(用户已被禁用)
  • BadCredentialsException(坏的凭据)
  • LockedException(账户锁定)
  • AccountExpiredException (账户过期)
  • CredentialsExpiredException(证书过期)


以上列出的这些异常都是 AuthenticationException 的子类,然后我们来看看 Spring security 如何处理 AuthenticationException 异常的。

二、源码分析

我们知道异常处理一般在过滤器中处理,我们在 AbstractAuthenticationProcessingFilter 中找到了对 AuthenticationException 的处理:

(1)在 doFilter() 中,捕捉了 AuthenticationException 异常,并交给了 unsuccessfulAuthentication() 处理。

(2)在 unsuccessfulAuthentication() 中,转交给了 SimpleUrlAuthenticationFailureHandler 类的 onAuthenticationFailure() 处理。

(3)在onAuthenticationFailure()中,首先判断有没有设置defaultFailureUrl。

  • 如果没有设置,直接返回 401 错误,即 HttpStatus.UNAUTHORIZED 的值。
  • 如果设置了,首先执行 saveException() 方法。然后判断 forwardToDestination ,即是否是服务器跳转,默认使用重定向即客户端跳转。

(4)在 saveException() 方法中,首先判断forwardToDestination,如果使用服务器跳转则写入 Request,客户端跳转则写入 Session。写入名为 SPRING_SECURITY_LAST_EXCEPTION ,值为 BadCredentialsException。

至此 Spring security 完成了异常处理,总结一下流程:

–> AbstractAuthenticationProcessingFilter.doFilter()

–> AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication()

–> SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure()

–> SimpleUrlAuthenticationFailureHandler.saveException()

三、处理异常

上面源码说了那么多,真正处理起来很简单,我们只需要指定错误的url,然后再该方法中对异常进行处理即可。

(1)指定错误Url,WebSecurityConfig中添加.failureUrl("/login/error")

...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 如果有允许匿名的url,填在下面
// .antMatchers().permitAll()
.anyRequest().authenticated()
.and()
// 设置登陆页
.formLogin().loginPage("/login")
// 设置登陆成功页
.defaultSuccessUrl("/").permitAll()
// 登录失败Url
.failureUrl("/login/error")
// 自定义登陆用户名和密码参数,默认为username和password
// .usernameParameter("username")
// .passwordParameter("password")
.and()
.logout().permitAll()
// 自动登录
.and().rememberMe()
.tokenRepository(persistentTokenRepository())
// 有效时间:单位s
.tokenValiditySeconds(60)
.userDetailsService(userDetailsService); // 关闭CSRF跨域
http.csrf().disable();
}
...

(2)在Controller中处理异常

@RequestMapping("/login/error")
public void loginError(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
AuthenticationException exception =
(AuthenticationException)request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
try {
response.getWriter().write(exception.toString());
}catch (IOException e) {
e.printStackTrace();
}
}

我们首先获取了 session 中的 SPRING_SECURITY_LAST_EXCEPTION 。为了演示,我只是简单的将错误信息返回给了页面。运行程序,当我们输入错误密码时:

---------------------
作者:Jitwxs
来源:CSDN
原文:https://blog.csdn.net/yuanlaijike/article/details/80250389

SpringBoot集成Spring Security(3)——异常处理的更多相关文章

  1. SpringBoot集成Spring Security(4)——自定义表单登录

    通过前面三篇文章,你应该大致了解了 Spring Security 的流程.你应该发现了,真正的 login 请求是由 Spring Security 帮我们处理的,那么我们如何实现自定义表单登录呢, ...

  2. SpringBoot集成Spring Security入门体验

    一.前言 Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权. 二者区别 Spring Security:重量级安全框架 Apache S ...

  3. SpringBoot集成Spring Security(7)——认证流程

    文章目录 一.认证流程 二.多个请求共享认证信息 三.获取用户认证信息 在前面的六章中,介绍了 Spring Security 的基础使用,在继续深入向下的学习前,有必要理解清楚 Spring Sec ...

  4. SpringBoot集成Spring Security(6)——登录管理

    文章目录 一.自定义认证成功.失败处理 1.1 CustomAuthenticationSuccessHandler 1.2 CustomAuthenticationFailureHandler 1. ...

  5. SpringBoot集成Spring Security(5)——权限控制

    在第一篇中,我们说过,用户<–>角色<–>权限三层中,暂时不考虑权限,在这一篇,是时候把它完成了. 为了方便演示,这里的权限只是对角色赋予权限,也就是说同一个角色的用户,权限是 ...

  6. SpringBoot集成Spring Security(2)——自动登录

    在上一章:SpringBoot集成Spring Security(1)——入门程序中,我们实现了入门程序,本篇为该程序加上自动登录的功能. 文章目录 一.修改login.html二.两种实现方式 2. ...

  7. SpringBoot 集成Spring security

    Spring security作为一种安全框架,使用简单,能够很轻松的集成到springboot项目中,下面讲一下如何在SpringBoot中集成Spring Security.使用gradle项目管 ...

  8. SpringBoot集成Spring Security

    1.Spring Security介绍 Spring security,是一个强大的和高度可定制的身份验证和访问控制框架.它是确保基于Spring的应用程序的标准 --来自官方参考手册 Spring ...

  9. SpringBoot集成Spring Security(1)——入门程序

    因为项目需要,第一次接触 Spring Security,早就听闻 Spring Security 功能强大但上手困难,学习了几天出入门道,特整理这篇文章希望能让后来者少踩一点坑(本文附带实例程序,请 ...

随机推荐

  1. VS 中批量格式化、删除未使用的 using 语句代码的插件

    插件名称:Format All Files 插件地址:https://marketplace.visualstudio.com/items?itemName=munyabe.FormatAllFile ...

  2. .net post请求webservice

    class Program { static void Main(string[] args) { , name = "jxp" }); var a = HttpHelper.Po ...

  3. .NET Core跨平台部署于Docker(Centos)- 视频教程

    (双击全屏播放) 往期教程: .NET开发框架(一)-框架介绍与视频演示 .NET开发框架(二)-框架功能简述 .NET开发框架(三)-高可用服务器端设计 .NET开发框架(四)-服务器IIS实践教程 ...

  4. RSA加密方法

    /// <summary>        /// RSA加密        /// </summary>        /// <param name="dat ...

  5. asp.net实现页面跳转后不可以返回

    window.history.go(0); Response.Write("<script> window.history.go(0);alert('恭喜user注册成功!!!\ ...

  6. 一款好用的SSH工具“FinalShell”

    FinalShell是一体化的的服务器,网络管理软件,不仅是ssh客户端,还是功能强大的开发,运维工具,充分满足开发,运维需求. 特色功能:免费海外服务器远程桌面加速,ssh加速,双边tcp加速,内网 ...

  7. APS系统对制造企业到底有多重要?看完这5点你就明白了

    第一个问题:需要APS吗? APS是否重要,不能从其所体现的软件工具或系统角度来说,而应该从业务角度来说.对于制造工厂和车间的运行而言,计划是核心的业务.就如同那句俗话说的,没有规矩不成方圆,领军打仗 ...

  8. Python odoo中嵌入html简单的分页功能

    在odoo中,通过iframe嵌入 html,页面数据则通过controllers获取,使用jinja2模板传值渲染 html页面分页内容,这里写了判断逻辑 <!-- 分页 -->< ...

  9. PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function【转】

    这篇文章主要介绍了PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function,需要的朋友可以参考下 1.错误类型:PHP致命错误 E ...

  10. maven的配置及基本操作

    ---恢复内容开始--- 1.官网下载maven 官方网址:http://maven.aparche.org 2.将maven解压到硬盘(最好没有中文路径)下 3.配置maven环境变量  4.配置m ...