当前位置:网站首页>自定义HandlerInterceptor拦截器实现用户鉴权
自定义HandlerInterceptor拦截器实现用户鉴权
2022-06-29 17:20:00 【拥抱白菜的猪】
拦截器常见的用途有:
1、日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。
2、权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面;
3、性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);
4、通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个处理器都需要的即可使用拦截器实现。
5、OpenSessionInView:如Hibernate,在进入处理器打开Session,在完成后关闭Session。
…………本质也是AOP(面向切面编程),也就是说符合横切关注点的所有功能都可以放入拦截器实现。
拦截器实现用户鉴权原理:
- 创建用在类上和方法上的自定义注解,用来决定这个方法的访问是否需要鉴权
- 自定义拦截器,坚定拦截到的请求是否需要鉴权,鉴权是否通过。
- 注册自定义的拦截器
下面以实现HandlerInterceptor拦截器为例
1、自定义注解
/**
* 自定义注解,用来表示方法活类是否需要鉴权
*/
@Target({ElementType.METHOD, ElementType.TYPE}) //指定注解的使用位置
@Retention(RetentionPolicy.RUNTIME) //指定注解的作用范围,代码运行时
public @interface UserLoginToken {
boolean required() default true; //默认为TRUE
}2、自定义拦截器,实现HandlerInterceptor接口
public class AuthenticationInterceptor implements HandlerInterceptor {
/**
* 该方法将在请求处理之前进行调用,用来坚定用户权限
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(object instanceof HandlerMethod)){
return true;
}
//获取请求的方法
HandlerMethod handlerMethod=(HandlerMethod)object;
Method method=handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
log.error("无token,请重新登录");
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
DecodedJWT decode = JWT.decode(token);
userId = decode.getAudience().get(0);
Date expiresAt = decode.getExpiresAt();//获取token过期时间
if (expiresAt.before(new Date())) {
log.error("token已过期,请重新登录");
throw new RuntimeException("token已过期,请重新登录");
}
} catch (Exception j) {
log.error("无token,请重新登录");
throw new RuntimeException("无token,请重新登录");
}
//根据从token中解析的userID判断用户是否存在
// ExTraderUser user = exTraderUserMapper.selectByCode(userId);
// ExUser exUserV2 = exUserMapper.selectByCode(userId);
// if (user == null && exUserV2 == null) {
// log.error("用户不存在,请重新登录");
// throw new RuntimeException("用户不存在,请重新登录");
// }
// if(Objects.isNull(user) && Objects.isNull(user.getTRADE_CENTER_NAME()) &&Objects.isNull(exUserV2) && Objects.isNull(exUserV2.getTRADE_CENTER_NAME())){
// log.error("用户不存在,请重新登录");
// throw new RuntimeException("用户不存在,请重新登录");
// }
try {
// 验证 token
if(user != null){
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getTRADE_CENTER_NAME())).build();
// jwtVerifier.verify(token); //根据令牌和签名解析数据
}
// if(exUserV2 != null){
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(exUserV2.getTRADE_CENTER_NAME())).build();
// jwtVerifier.verify(token); //根据令牌和签名解析数据
}
} catch (Exception e) {
log.error("无token,请重新登录");
throw new RuntimeException("无token,请重新登录");
}
// UserConfig.setUser(exUserV2);
return true;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
UserConfig.removeUser();
}
}3、注册自定义拦截器
有了拦截器PasswordStateInterceptor,还需要对拦截器进行注册。需要使用WebMvcConfigurerAdapter 下的addInterceptors方法。 新建一个类WebConfigfilter.java,继承自WebMvcConfigurerAdapter 。
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}拦截器HandlerInterceptor有三个方法:
- preHandle
- postHandle
- afterCompletion
(1)preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) 方法,顾名思义,该方法将在请求处理之前进行调用。SpringMVC 中的Interceptor 是链式的调用的,在一个应用中或者说是在一个请求中可以同时存在多个Interceptor 。每个Interceptor 的调用会依据它的声明顺序依次执行,而且最先执行的都是Interceptor 中的preHandle 方法,所以可以在这个方法中进行一些前置初始化操作或者是对当前请求的一个预处理,也可以在这个方法中进行一些判断来决定请求是否要继续进行下去。该方法的返回值是布尔值Boolean 类型的,当它返回为false 时,表示请求结束,后续的Interceptor 和Controller 都不会再执行;当返回值为true 时就会继续调用下一个Interceptor 的preHandle 方法,如果已经是最后一个Interceptor 的时候就会是调用当前请求的Controller 方法。
(2)postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) 方法,由preHandle 方法的解释我们知道这个方法包括后面要说到的afterCompletion 方法都只能是在当前所属的Interceptor 的preHandle 方法的返回值为true 时才能被调用。postHandle 方法,顾名思义就是在当前请求进行处理之后,也就是Controller 方法调用之后执行,但是它会在DispatcherServlet 进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作。postHandle 方法被调用的方向跟preHandle 是相反的,也就是说先声明的Interceptor 的postHandle 方法反而会后执行,这和Struts2 里面的Interceptor 的执行过程有点类型。Struts2 里面的Interceptor 的执行过程也是链式的,只是在Struts2 里面需要手动调用ActionInvocation 的invoke 方法来触发对下一个Interceptor 或者是Action 的调用,然后每一个Interceptor 中在invoke 方法调用之前的内容都是按照声明顺序执行的,而invoke 方法之后的内容就是反向的。
(3)afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) 方法,该方法也是需要当前对应的Interceptor 的preHandle 方法的返回值为true 时才会执行。顾名思义,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。这个方法的主要作用是用于进行资源清理工作的。
边栏推荐
- MySQL highly available cluster – MHA
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- Leetcode daily question - 535 Encryption and decryption of tinyurl
- Redis principle - sorted set (Zset)
- 基于C语言开发实现的一个用户级线程库
- 适合中小企业的项目管理系统有哪些?
- 从居家办公中感悟适配器模式 | 社区征文
- 2020版KALI安装教程
- AI and creativity
- Bags of Binary Words for Fast Place Recognition in Image Sequenc
猜你喜欢

腾讯云发布自动化交付和运维产品Orbit,推动企业应用全面云原生化

使用kalibr標定工具進行單目相機和雙目相機的標定

LeetCode 每日一题——535. TinyURL 的加密与解密
![[R language data science]: Text Mining (taking Trump's tweet data as an example)](/img/4f/09b9885915bee50fb40976a5002730.png)
[R language data science]: Text Mining (taking Trump's tweet data as an example)

ICML 2022 | transferable imitation learning method based on decoupling gradient optimization

mysql如何查询表的字符集编码

机器学习8-人工神经网络

自动收售报机

What is the follow-up plan of infotnews | meta in the metauniverse?

Automatic vending machine
随机推荐
外部自动(PLC启动机器人)
Summary of problems during xampp Apache installation
关于harbor私有仓库忘记登录密码
mysql数据库扫盲,你真的知道什么是数据库嘛
Kubernetes deployment dashboard (Web UI management interface)
An error is reported in the Flink SQL rownumber. Who has met him? How to solve it?
在线SQL转CSV工具
Fluent的msh格式网格学习
535. TinyURL 的加密与解密 / 剑指 Offer II 103. 最少的硬币数目
Redis principle - sorted set (Zset)
Shenzhen internal promotion | Shenzhen Institute of computing science recruits assistant machine learning Engineer (school recruitment)
手把手教你在windows上安装mysql8.0最新版本数据库,保姆级教学
NVIDIA安装最新显卡驱动
Gradle download slow or unable to download
SpingMVC请求和响应
LSB hidden items of stream carrier based on assembly implementation
垃圾收集器
How to use interrupt
Help MySQL data analysis with databend
2020版KALI安装教程