How SpringBoot implements login interception through ThreadLocal
1 Preface
Registration and login can be said to be the most common thing in daily development, but generally after entering the company, functions like this have long been available Development is complete, unless it is a new project. In the past two days, I happened to encounter such a need to complete the registration and login function on the PC side.
There are many ways to achieve such a requirement: like
1) HandlerInterceptor WebMvcConfigurer ThreadLocal
2) Filter filter
3) Security Framework Shiro ( Lightweight framework)
4) Security framework Spring Securety (heavyweight framework)
And I use the first Spring HandlerInterceptor WebMvcConfigurer ThreadLocal technology to implement it.
2 Concrete class
2.1HandlerInterceptor
HandlerInterceptor is the interface provided for interceptors in springMVC. It is similar to the filter Filter in Servlet development and is used for preprocessing by the processor. For processing and post-processing, three methods need to be rewritten.
preHandle:
Calling time: before controller method processing
Execution order: In the case of chained Intercepter, the Intercepters are executed one after another in the order of declaration
If false is returned, execution will be interrupted. Note: it will not enter afterCompletion
postHandle:
Calling premise: preHandle returns true
Calling time: After the Controller method is processed, DispatcherServlet Before rendering the view, that is to say, you can operate ModelAndView in this method.
Execution order: In the case of chained Interceptor, the Intercepter is executed in the order of declaration.
Remarks: Although postHandle starts with post , but both post requests and get requests can be processed
afterCompletion:
Calling premise: preHandle returns true
Calling time: after DispatcherServlet renders the view
Mostly used to clean up resources
2.2WebMvcConfigurer
WebMvcConfigurer configuration class is actually an internal configuration method of Spring
, using the form of JavaBean
instead The traditional xml
configuration file format is customized for the framework. Some Handlers, Interceptors, ViewResolvers, and MessageConverters can be customized. For spring mvc configuration based on java-based method, you need to create a configuration class and implement the WebMvcConfigurer
interface;
in Spring Boot 1.5 version relies on rewriting the method of WebMvcConfigurerAdapter to add custom interception converter, message converter, etc. After SpringBoot 2.0 version, this class has been marked @Deprecated (deprecated). The official recommendation is to directly implement WebMvcConfigurer or directly inherit WebMvcConfigurationSupport. The first method is to implement the WebMvcConfigurer interface (recommended), and the second method is to inherit the WebMvcConfigurationSupport class
3 Code practice
1) Write the interceptor HeadTokenInterceptor so that it inherits HandlerInterceptor
package com.liubujun.config; import com.liubujun.moudle.UserToken; import com.liubujun.util.SecurityContextUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.handler.Handler; import java.io.IOException; /** * @Author: liubujun * @Date: 2022/5/21 16:12 */ @Component @Slf4j public class HeadTokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String authorization = request.getHeader("Authorization"); if (authorization == null ) { unauthorized(response); return false; } //这里一般都会解析出userToken的值,这里为了方便就直接new了 UserToken userToken = new UserToken(); SecurityContextUtil.addUser(userToken); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { SecurityContextUtil.removeUser(); } private void unauthorized(HttpServletResponse response) { response.setStatus(HttpStatus.UNAUTHORIZED.value()); try { response.getWriter().append(HttpStatus.UNAUTHORIZED.getReasonPhrase()); } catch (IOException e) { log.error("HttpServletResponse writer error.msg",HttpStatus.UNAUTHORIZED.getReasonPhrase()); log.error(e.getMessage(),e); } } }
2) Write MyWebMvcConfigurer to inherit WebMvcConfigurationSupport
package com.liubujun.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.ArrayList; /** * @Author: liubujun * @Date: 2022/5/21 16:40 */ @Configuration public class MyWebMvcConfigurer extends WebMvcConfigurationSupport { @Autowired private HeadTokenInterceptor headTokenInterceptor; /** * 类似于白名单,在这边添加的请求不会走拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { ArrayList<String> pattres = new ArrayList<>(); pattres.add("/login/login"); registry.addInterceptor(headTokenInterceptor).excludePathPatterns(pattres).addPathPatterns("/**"); super.addInterceptors(registry); } /** * 添加静态资源 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("xxx.html") .addResourceLocations("classpath:/META-INF/resources"); super.addResourceHandlers(registry); } }
3) Write the ThreadLocal class to store user information
package com.liubujun.util; import com.liubujun.moudle.UserToken; import org.springframework.core.NamedThreadLocal; /** * @Author: liubujun * @Date: 2022/5/23 9:41 */ public class SecurityContextUtil { private static ThreadLocal<UserToken> threadLocal = new NamedThreadLocal<>("user"); public static void addUser(UserToken user){ threadLocal.set(user); } public static UserToken getUser(){ return threadLocal.get(); } public static void removeUser(){ threadLocal.remove(); } public static String getPhoneNumber(){ return threadLocal.get().getPhoneNumber(); } public static Integer getId(){ return threadLocal.get().getId(); } public static String getUserText(){ return threadLocal.get().getUserText(); } }
4) Write a test controller
@RestController @RequestMapping(value = "/login",produces = {"application/json;charset=UTF-8"}) public class Login { @PostMapping("/login") public String login(){ return "登录请求不需要拦截"; } @PostMapping("/other") public String other(){ return "其他的请求需要拦截"; } }
5) Test
Test the login interface, (lead directly without passing the token)
Test other interfaces, if the token is not passed, it will be intercepted
The above is the detailed content of How SpringBoot implements login interception through ThreadLocal. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
