文章有不当之处,欢迎指正,如果喜欢微信阅读,你也可以关注我的微信公众号:好好学java,获取优质学习资源。

一、spring Aop身份验证

一般,如果用户没有登录的话,用户只可以查看商品,但是其他的,比如支付等是不能够进行操作的,这个时候,我们就需要用到用户拦截, 或者说身份验证了。

首先定义一个类AuthorizeAspect,以@Aspect注解。

然后把所有以Controller声明为切点,但排除UserController,因为这个Controller就是验证用户登录的Controller。

  @Pointcut("execution(public * com.sihai.controller *.*(..))"+"&& !execution(public * com.sihai.controller.UserController.*(..))")public void verify(){}

最后对这个切点做一些前置处理,因为用户登录后,按照我们之前写的逻辑,cookie和redis中应该含有用户的信息,所以现在查询这两个地方,来验证用户有没有登录。

   @Before("verify()")public void doVerify(){ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request=attributes.getRequest();//查询cookieCookie cookie= CookieUtil.get(request,CookieConstant.TOKEN);if (cookie==null){log.warn("Cookie中查不到token");throw new   AuthorizeException();}//去redis查询,这个下面的redis用到的是springboot的redis工具类String tokenValue=redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if (StringUtils.isEmpty(tokenValue)){log.warn("Redis中查不到token");throw new   AuthorizeException();}}

完整代码如下:

@Aspect
@Component
@Slf4j
public class AuthorizeAspect {@Autowiredprivate StringRedisTemplate redisTemplate;@Pointcut("execution(public * com.sihai.controller.  *.*(..))"+"&& !execution(public * com.sihai.controller.  UserController.*(..))")public void verify(){}@Before("verify()")public void doVerify(){ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request=attributes.getRequest();//查询cookieCookie cookie= CookieUtil.get(request,CookieConstant.TOKEN);if (cookie==null){log.warn(" Cookie中查不到token");throw new   AuthorizeException();}//去redis查询String tokenValue=redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if (StringUtils.isEmpty(tokenValue)){log.warn("  Redis中查不到token");throw new   AuthorizeException();}}}

二、springboot统一异常处理

  • 自定义异常类

从以上代码中可以看到,如果用户没有登陆,就会抛出一个 AuthorizeException的异常,这是一个自定义的异常。这个异常很简单,只有一个简单的定义,为运行时异常

public class AuthorizeException extends RuntimeException {}

之后我们需要定义一个对这个异常的处理器 ExceptionHandler,当扑获到这个异常,说明用户没有登陆,那就重新调到登陆界面(访问处理登陆的Controller)。

  • 创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类,而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型,最后将Exception对象和请求URL映射到error.html
@ControllerAdvice
public class  ExceptionHandler {@Autowiredprivate ProjectUrlConfig projectUrlConfig;//拦截登录异常@ExceptionHandler(value =  AuthorizeException.class)public ModelAndView handlerAuthorizeException(){ModelAndView mav = new ModelAndView();mav.addObject("exception", e);mav.addObject("url", req.getRequestURL());mav.setViewName(DEFAULT_ERROR_VIEW);return mav;}
}
  • 实现error.html页面展示:在templates目录下创建error.html,将请求的URL和Exception对象的message输出。
<!DOCTYPE html>
<html>
<head lang="en"><meta charset="UTF-8" /><title>统一异常处理</title>
</head>
<body><h1>Error Handler</h1><div th:text="${url}"></div><div th:text="${exception.message}"></div>
</body>
</html>

启动该应用,访问:http://localhost:8080/hello,可以看到如下错误提示页面。

spring Aop实现身份验证和springboot异常统一处理相关推荐

  1. Spring——AOP配置时的jar包异常

    Spring--AOP配置时的jar包异常 参考文章: (1)Spring--AOP配置时的jar包异常 (2)https://www.cnblogs.com/dyllove98/p/3180193. ...

  2. java授权失败_自定义Spring Security的身份验证失败处理方法

    1.概述 在本快速教程中,我们将演示如何在Spring Boot应用程序中自定义Spring Security的身份验证失败处理.目标是使用表单登录方法对用户进行身份验证. 2.认证和授权(Authe ...

  3. Spring Security:身份验证入口AuthenticationEntryPoint介绍与Debug分析

    ExceptionTranslationFilter ExceptionTranslationFilter(Security Filter)允许将AccessDeniedException和Authe ...

  4. Spring Security:身份验证令牌Authentication介绍与Debug分析

    在Spring Security中,通过Authentication来封装用户的验证请求信息,Authentication可以是需要验证和已验证的用户请求信息封装.接下来,博主介绍Authentica ...

  5. apache过滤恶意频繁访问_采用网关过滤器实现权限验证及对异常统一处理

    采用网关过滤器实现权限验证 1.创建 zuul 项目 2.修改 pom.xml 文件 <project xmlns="http://maven.apache.org/POM/4.0.0 ...

  6. Spring Security:探索 JDBC 身份验证

    1. 概述 在这个简短的教程中,我们将探讨 Spring 提供的使用现有数据源配置执行 JDBC 身份验证的功能. 在我们的"使用数据库支持的用户详细信息服务进行身份验证"一文中, ...

  7. 使用Spring Security进行简单身份验证

    朋友不允许朋友写用户身份验证. 厌倦了管理自己的用户? 立即尝试Okta的API和Java SDK. 在几分钟之内即可对任何应用程序中的用户进行身份验证,管理和保护. 身份验证对于除了最基本的Web应 ...

  8. HttpMoudle实现用户身份验证

      查看文章   HttpMoudle实现用户身份验证 2009-12-04 19:37 参考自小白.net的HttpMoudle实现用户身份验证 下表列出了在 IIS 7.0 集成模式下运行的 AS ...

  9. ASP.Net 2.0窗体身份验证机制详解(FormsAuthentication) (转载)

    ASP.Net 2.0窗体身份验证机制详解(FormsAuthentication) 收藏 转自:http://www.aspxclub.com/l12/c_3689.html 本篇文章介绍了在ASP ...

最新文章

  1. 深入思考编译原理之 理解执行过程和编译过程
  2. mysql 判断表或字段存不存在
  3. 2021-2022年度第三届全国大学生算法设计与编程挑战赛(秋季赛)- 分组(矩阵快速幂套NTT优化dp)
  4. oracle unpivot 索引_oracle 11g 行列转换之unpivot、pivot
  5. Sql Server之旅——第十三站 深入的探讨锁机制
  6. css img 适配尺寸_CSS容易使人蒙圈的几个经典问题
  7. 13 | 线性排序:如何根据年龄给100万用户数据排序?
  8. 腾讯的强大不是偶然,小马哥很强大
  9. 作者:潘永花,阿里数据经济研究中心秘书长,阿里研究院高级专家。
  10. 《大数据》第2期“专题”——数据开放与政府治理创新
  11. python之FTP程序(支持多用户在线)
  12. [GCN+FocalLoss] 从数据角度分析实验 of Semi-supervised classification with graph convolutional networks
  13. Educational Codeforces Round 12 F. Four Divisors 求小于x的素数个数(待解决)
  14. 怎么锁定计算机密码忘了怎么办,电脑在控制面板被锁密码忘记怎么开呢?
  15. 16秋计算机JAVA第一节课作业(钟永钜)
  16. win7锁定该计算机快捷键,Win7电脑锁定计算机快捷键的方法.ppt
  17. 【scala】获取当前时间的上一个自然周以及自然周集合;获取当前时间的上一个自然月以及自然月的第一天与最后一天
  18. 画E-R图·数据库笔记(四)
  19. 直插电阻通过色环读取电阻阻值,误差与温度系数方法总结
  20. 基于Stanford Parser 及OpenNLP Shallow Parser构建句子语法解析树

热门文章

  1. 设计模式总结 (2)创建型模式
  2. 基于区块链的健康链系统设计与实现(6)结束语
  3. 现代密码学5.5--Random-Oracle模型
  4. Kubernetes存储之PV-PVC
  5. 10-Platform Interrupt Controller API
  6. Device is not certified by Google
  7. 833c语言程序是什么,江南大学
  8. linux运维防火墙考题,Linux运维工程师:30道面试题整理 | 张戈博客
  9. 安洵杯——game(混淆控制流平坦化)
  10. final、finally、finalize的区别