当前位置:网站首页>Custom handlerinterceptor interceptor for user authentication
Custom handlerinterceptor interceptor for user authentication
2022-06-29 17:21:00 【Pig hugging cabbage】
Common uses of interceptors are :
1、 logging : Log request information , For information monitoring 、 Information Statistics 、 Calculation PV(Page View) etc. .
2、 Permission check : Such as login detection , Enter the processor to detect whether to log in , If you don't go back to the login page ;
3、 Performance monitoring : Sometimes the system is inexplicably slow for a certain period of time , You can use the interceptor to record the start time before entering the processor , Record the end time after processing , Thus, the processing time of the request ( If there is a reverse proxy , Such as apache It can be recorded automatically );
4、 General behavior : Read cookie Get the user information and put the user object in the request , So as to facilitate the use of subsequent processes , There is also extraction Locale、Theme Information, etc , As long as multiple processors need to be able to use interceptors to achieve .
5、OpenSessionInView: Such as Hibernate, On entering the processor Session, Close on completion Session.
………… Essence is also AOP( Section oriented programming ), That is to say, all functions that conform to crosscutting concerns can be implemented in interceptors .
The interceptor implements the principle of user authentication :
- Create custom annotations for classes and methods , Used to determine whether the access of this method requires authentication
- Custom interceptors , Whether authentication is required for firmly intercepted requests , Authentication passed .
- Register a custom interceptor
Let's implement HandlerInterceptor For example, interceptors
1、 Custom annotation
/**
* Custom annotation , Used to indicate whether the method class needs authentication
*/
@Target({ElementType.METHOD, ElementType.TYPE}) // Specify where annotations are used
@Retention(RetentionPolicy.RUNTIME) // Specify the scope of the annotation , Code runtime
public @interface UserLoginToken {
boolean required() default true; // The default is TRUE
}2、 Custom interceptors , Realization HandlerInterceptor Interface
public class AuthenticationInterceptor implements HandlerInterceptor {
/**
* This method is called before the request is processed , Used to enforce user rights
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader("token");// from http Take it out of the request head token
// If it's not mapped to a method directly through
if(!(object instanceof HandlerMethod)){
return true;
}
// How to get the request
HandlerMethod handlerMethod=(HandlerMethod)object;
Method method=handlerMethod.getMethod();
// Check if there is passtoken notes , If yes, skip Authentication
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
// Check for comments that require user authority
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// Perform Certification
if (token == null) {
log.error(" nothing token, Please login again ");
throw new RuntimeException(" nothing token, Please login again ");
}
// obtain token Medium user id
String userId;
try {
DecodedJWT decode = JWT.decode(token);
userId = decode.getAudience().get(0);
Date expiresAt = decode.getExpiresAt();// obtain token Expiration time
if (expiresAt.before(new Date())) {
log.error("token Has expired , Please login again ");
throw new RuntimeException("token Has expired , Please login again ");
}
} catch (Exception j) {
log.error(" nothing token, Please login again ");
throw new RuntimeException(" nothing token, Please login again ");
}
// According to from token Parsed in userID Judge whether the user exists
// ExTraderUser user = exTraderUserMapper.selectByCode(userId);
// ExUser exUserV2 = exUserMapper.selectByCode(userId);
// if (user == null && exUserV2 == null) {
// log.error(" The user doesn't exist , Please login again ");
// throw new RuntimeException(" The user doesn't exist , Please login again ");
// }
// if(Objects.isNull(user) && Objects.isNull(user.getTRADE_CENTER_NAME()) &&Objects.isNull(exUserV2) && Objects.isNull(exUserV2.getTRADE_CENTER_NAME())){
// log.error(" The user doesn't exist , Please login again ");
// throw new RuntimeException(" The user doesn't exist , Please login again ");
// }
try {
// verification token
if(user != null){
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getTRADE_CENTER_NAME())).build();
// jwtVerifier.verify(token); // Parse data based on token and signature
}
// if(exUserV2 != null){
// JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(exUserV2.getTRADE_CENTER_NAME())).build();
// jwtVerifier.verify(token); // Parse data based on token and signature
}
} catch (Exception e) {
log.error(" nothing token, Please login again ");
throw new RuntimeException(" nothing token, Please login again ");
}
// 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、 Register a custom interceptor
With the interceptor PasswordStateInterceptor, You also need to register the interceptor . Need to use WebMvcConfigurerAdapter Under the addInterceptors Method . Create a new class WebConfigfilter.java, Inherited from WebMvcConfigurerAdapter .
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**"); // Intercept all requests , By judging whether there is @LoginRequired annotation Decide if you need to log in
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}Interceptor HandlerInterceptor There are three ways :
- preHandle
- postHandle
- afterCompletion
(1)preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) Method , seeing the name of a thing one thinks of its function , This method is called before the request is processed .SpringMVC Medium Interceptor It's a chain call , In an application or in a request, there can be more than one Interceptor . Every Interceptor Calls to are executed in the order in which they are declared , And the first ones are Interceptor Medium preHandle Method , So you can do some pre initialization operations or a pre-processing of the current request in this method , You can also make some judgments in this method to determine whether the request will continue . The return value of this method is a Boolean value Boolean Type of , When it returns to false when , End of request , Follow up Interceptor and Controller No more ; When the return value is true Will continue to call the next Interceptor Of preHandle Method , If it's the last one Interceptor It will call the current request Controller Method .
(2)postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) Method , from preHandle We know that this method includes the following afterCompletion Methods can only belong to the Interceptor Of preHandle The return value of the method is true Can be called .postHandle Method , As the name suggests, after the current request is processed , That is to say Controller Method is executed after the call , But it will DispatcherServlet Called before view return rendering , So we can do it in this way Controller After processing ModelAndView Object to operate on .postHandle Method is called in the same direction as preHandle It's the opposite , That is to say, it should be declared first Interceptor Of postHandle Methods will be implemented later , This sum Struts2 Inside Interceptor There's a bit of a typology in the execution of .Struts2 Inside Interceptor The execution process is also chained , It's just Struts2 It needs to be called manually ActionInvocation Of invoke Method to trigger the next Interceptor Or is it Action Call to , And then every one Interceptor In the invoke The contents before the method call are executed in the order of declaration , and invoke After that, the way to reverse the content .
(3)afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) Method , This method also needs the current corresponding Interceptor Of preHandle The return value of the method is true Only when . seeing the name of a thing one thinks of its function , This method will be used after the end of the entire request , That is to say DispatcherServlet Execute after rendering the corresponding view . The main purpose of this method is to clean up resources .
边栏推荐
- R语言使用自定义函数编写深度学习线性激活函数、并可视化线性激活函数
- Bags of Binary Words for Fast Place Recognition in Image Sequenc
- Viewing splitchunks code segmentation from MPX resource construction optimization
- 使用 SSH 方式拉取代码
- Master slave replication of MySQL
- 可转债策略之---(摊饼玩法,溢价玩法,强赎玩法,下修玩法,双低玩法)
- mysql.sock的概念是什么
- Tencent cloud released orbit, an automated delivery and operation and maintenance product, to promote enterprise applications to be fully cloud native
- KUKA机器人外部轴配置你一定要知道的那些知识
- 卷妹带你学数据库---5天冲刺Day4
猜你喜欢

0基础自学STM32(野火)——寄存器点亮LED

LeetCode 每日一题——535. TinyURL 的加密与解密

ICML 2022 | 基于解耦梯度优化的可迁移模仿学习方法

Word2vec vector model of Wiki Chinese corpus based on deep learning

Naacl 2022 | distillation of machinetranslation SOTA model

手把手教你在windows上安装mysql8.0最新版本数据库,保姆级教学

Online text digit recognition list summation tool

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

mysql支持外键吗

微信小程序开发储备知识
随机推荐
自旋电子学笔记-张曙丰
卷妹带你学jdbc—2天冲刺Day1
mysql视图能不能创建索引
mysql游标的作用是什么
C language practice ---- pointer string and linked list
When MySQL RDS is collected using Flink CDC, the datetime type field will be compared with the source table after collection
R语言将距离矩阵输入给hclust函数进行层次聚类分析,method参数指定两个组合数据点间的距离计算方式、plot函数可视化层次聚类的树状图(dendrogram)
Mysql中锁的使用场景是什么
First batch! Tencent cloud's ability to pass the solution of the government affairs collaboration platform of the China Academy of ICT
力扣解法汇总535-TinyURL 的加密与解密
关于KALI使用xshell连接
第42期:MySQL 是否有必要多列分区
ICML 2022 | transferable imitation learning method based on decoupling gradient optimization
Error:Connection refused: connect
Subgraphs in slam
函数计算异步任务能力介绍 - 任务触发去重
mysql在linux中2003错误如何解决
正则表达式
微博评论高性能高可用架构设计(架构实战营 模块五作业)
R语言使用MASS包的glm.nb函数建立负二项广义线性模型(negative binomial)、summary函数获取负二项广义线性模型模型汇总统计信息