资讯专栏INFORMATION COLUMN

Spring Security中异常上抛机制及对于转型处理的一些感悟

tracymac7 / 2943人阅读

摘要:如子异常都可以向上转型为统一的验证异常。在设计之初的时候,验证类统一的父级异常是。两个场景下的异常类关系图谱通过上面的图谱我们便知道了,三个异常都可以向上转型为。向下转型调整后的代码在外层根据不同异常而做不同的业务处理的代码就可以改造为如下

引言

在使用Spring Security的过程中,我们会发现框架内部按照错误及问题出现的场景,划分出了许许多多的异常,但是在业务调用时一般都会向外抛一个统一的异常出来,为什么要这样做呢,以及对于抛出来的异常,我们又该如何分场景进行差异化的处理呢,今天来跟我一起看看吧。

Spring Security框架下的一段登录代码

</>复制代码

  1. @PostMapping("/login")
  2. public void login(@NotBlank String username,
  3. @NotBlank String password, HttpServletRequest request) {
  4. try {
  5. request.login(username, password);
  6. System.out.println("login success");
  7. } catch (ServletException authenticationFailed) {
  8. System.out.println("a big exception authenticationFailed");
  9. }
  10. }

代码执行到request.login(username,password)时会跳入到了HttpServlet3RequestFactory类中,点击去发现login方法只是统一向外抛出了一个ServletException异常。

</>复制代码

  1. public void login(String username, String password) throws ServletException {
  2. if (this.isAuthenticated()) {
  3. throw new ServletException("Cannot perform login for "" + username + "" already authenticated as "" + this.getRemoteUser() + """);
  4. } else {
  5. AuthenticationManager authManager = HttpServlet3RequestFactory.this.authenticationManager;
  6. if (authManager == null) {
  7. HttpServlet3RequestFactory.this.logger.debug("authenticationManager is null, so allowing original HttpServletRequest to handle login");
  8. super.login(username, password);
  9. } else {
  10. Authentication authentication;
  11. try {
  12. authentication = authManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
  13. } catch (AuthenticationException var6) {
  14. SecurityContextHolder.clearContext();
  15. throw new ServletException(var6.getMessage(), var6);
  16. }
  17. SecurityContextHolder.getContext().setAuthentication(authentication);
  18. }
  19. }
  20. } 

authenticate()为账号校验的主方法,进入到其中的一个实现类ProviderManager中,会发现方法实际抛出是统一抛出的AuthenticationException异常,方法体内实则会出现很多的场景性的异常,如AccountStatusException、InternalAuthenticationServiceException等等。

</>复制代码

  1. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  2. Class toTest = authentication.getClass();
  3. AuthenticationException lastException = null;
  4. Authentication result = null;
  5. boolean debug = logger.isDebugEnabled();
  6. Iterator var6 = this.getProviders().iterator();
  7. while(var6.hasNext()) {
  8. AuthenticationProvider provider = (AuthenticationProvider)var6.next();
  9. if (provider.supports(toTest)) {
  10. if (debug) {
  11. logger.debug("Authentication attempt using " + provider.getClass().getName());
  12. }
  13. try {
  14. result = provider.authenticate(authentication);
  15. if (result != null) {
  16. this.copyDetails(authentication, result);
  17. break;
  18. }
  19. } catch (AccountStatusException var11) {
  20. this.prepareException(var11, authentication);
  21. throw var11;
  22. } catch (InternalAuthenticationServiceException var12) {
  23. this.prepareException(var12, authentication);
  24. throw var12;
  25. } catch (AuthenticationException var13) {
  26. lastException = var13;
  27. }
  28. }
  29. }
  30. if (result == null && this.parent != null) {
  31. try {
  32. result = this.parent.authenticate(authentication);
  33. } catch (ProviderNotFoundException var9) {
  34. ;
  35. } catch (AuthenticationException var10) {
  36. lastException = var10;
  37. }
  38. }
  39. if (result != null) {
  40. if (this.eraseCredentialsAfterAuthentication && result instanceof CredentialsContainer) {
  41. ((CredentialsContainer)result).eraseCredentials();
  42. }
  43. this.eventPublisher.publishAuthenticationSuccess(result);
  44. return result;
  45. } else {
  46. if (lastException == null) {
  47. lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
  48. }
  49. this.prepareException((AuthenticationException)lastException, authentication);
  50. throw lastException;
  51. }
  52. }
多态和向上转型介绍

这里就涉及到了多态的知识点,异常的多态。如子异常AccountStatusException都可以向上转型为统一的验证异常AuthenticationException。

在设计之初的时候,验证类统一的父级异常是AuthenticationException。然后根据业务需求向下拓展出了很多个场景性质的异常,可能有十个、一百个、一千个。

但是这些具体的场景异常都是从AuthenticationException延伸出来的。

在这个验证登陆的方法中,会验证各种场景下登陆是否合法,就有可能出现很多的异常场景,诸如:

密码不正确 BadCredentialsException

账号是否被锁定 LockedException

账号是否被禁用 DisabledException

账号是否在有效期内 AccountExpiredException

密码失效 CredentialsExpiredException

...几十个几百个异常,如果每个都需要事无巨细的抛出,那你需要在方法后面写几百个异常。

但是你会发现在验证方法那里统一抛出的是他们的统一父类AuthenticationException,这里用到的就是自动的向上转型。
到业务层我们拿到AuthenticationException后,需要进行对特定场景下的业务处理,如不同的异常错误返回提示不一样,这个时候就需要用到向下转型。

</>复制代码

  1. Throwable throwable = authenticationFailed.getRootCause();
  2. if (throwable instanceof BadCredentialsException) {
  3. do something...
  4. }

如果父类引用实际指的是凭证错误,则进行密码错误提示。
ServletException和AuthenticationException是两个框架下的特定场景下的顶级异常,两个怎么建立联系呢?
答曰:直接将两个都统一转为Throwable可抛出的祖先异常,这样向下都可以转成他们自己了,以及各自场景下的所有异常了。

两个场景下的异常类关系图谱

通过上面的图谱我们便知道了,ServletException、BadCredentialsException、DisabledException三个异常都可以向上转型为Throwable。
那是在哪里进行的向上类型转换的呢?
答曰:

</>复制代码

  1. public void login(String username, String password) throws ServletException{
  2. something code ...
  3. catch (AuthenticationException loginFailed) {
  4. SecurityContextHolder.clearContext();
  5. throw new ServletException(loginFailed.getMessage(), loginFailed);
  6. }
  7. }
  8. // 在捕获到异常之后会构建一个ServletException并将AuthenticationException统一的包装进去,比如说内部报了BadCredentialsException,那么在这里就会向上转型为Throwable
  9. public ServletException(String message, Throwable rootCause) {
  10. super(message, rootCause);
  11. }
  12. // 在Throwable类中会将最下面冒出来的异常传给cause,getRootCause就能获得异常的具体原因
  13. public Throwable(String message, Throwable cause) {
  14. fillInStackTrace();
  15. detailMessage = message;
  16. this.cause = cause;
  17. }

在外层逻辑处理时,针对不同的业务场景我们便可以通过向下类型转化来完成,如使用instanceof来验证对象是否是子类的实例。

</>复制代码

  1. // Throwable向下转型BadCredentialsException
  2. if (throwable instanceof BadCredentialsException)
调整后的代码

在外层根据不同异常而做不同的业务处理的代码就可以改造为如下

</>复制代码

  1. @PostMapping("/login")
  2. public void login(@NotBlank String username,
  3. @NotBlank String password, HttpServletRequest request) {
  4. try {
  5. request.login(username, password);
  6. System.out.println("login success");
  7. } catch (ServletException authenticationFailed) {
  8. Throwable throwable = authenticationFailed.getRootCause();
  9. if (throwable instanceof BadCredentialsException) {
  10. System.out.println("user password is wrong");
  11. }else if (throwable instanceof DisabledException){
  12. System.out.println("user is disabled");
  13. }else {
  14. System.out.println("please contact the staff");
  15. }
  16. }
  17. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72381.html

相关文章

  • Java经典

    摘要:请注意,我们在聊聊单元测试遇到问题多思考多查阅多验证,方能有所得,再勤快点乐于分享,才能写出好文章。单元测试是指对软件中的最小可测试单元进行检查和验证。 JAVA容器-自问自答学HashMap 这次我和大家一起学习HashMap,HashMap我们在工作中经常会使用,而且面试中也很频繁会问到,因为它里面蕴含着很多知识点,可以很好的考察个人基础。但一个这么重要的东西,我为什么没有在一开始...

    xcold 评论0 收藏0
  • 使用Java Exception机制正确姿势

    摘要:如何良好的在代码中设计异常机制本身设计的出发点是极好的,通过编译器的强制捕获,可以明确提醒调用者处理异常情况。但使用此种异常后,该会像病毒一样,得不到处理后会污染大量代码,同时也可能因为调用者的不当处理,会失去异常信息。 1、异常是什么? 父类为Throwable,有Error和Exception两个子类 Error为系统级别的异常(错误) Exception下有众多子类,常见的有Ru...

    Astrian 评论0 收藏0
  • Java面试 32个核心必考点完全解析

    摘要:如问到是否使用某框架,实际是是问该框架的使用场景,有什么特点,和同类可框架对比一系列的问题。这两个方向的区分点在于工作方向的侧重点不同。 [TOC] 这是一份来自哔哩哔哩的Java面试Java面试 32个核心必考点完全解析(完) 课程预习 1.1 课程内容分为三个模块 基础模块: 技术岗位与面试 计算机基础 JVM原理 多线程 设计模式 数据结构与算法 应用模块: 常用工具集 ...

    JiaXinYi 评论0 收藏0
  • 关于web.xml配置那些事儿

    摘要:的版本增加了对事件监听程序的支持,事件监听程序在建立修改和删除会话或环境时得到通知。元素指出事件监听程序类。过滤器配置将一个名字与一个实现接口的类相关联。 1.简介 web.xml文件是Java web项目中的一个配置文件,主要用于配置欢迎页、Filter、Listener、Servlet等,但并不是必须的,一个java web项目没有web.xml文件照样能跑起来。Tomcat容器/...

    zhichangterry 评论0 收藏0

发表评论

0条评论

tracymac7

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<