Preface
In Spring Boot projects, Token verification is a common way to protect interface security. If each interface writes the Token verification logic separately, it will cause redundant code and be difficult to maintain. To solve this problem, you canInterceptororFilterImplement global Token verification, thereby uniformly processing the verification logic of all interfaces.
This article will provide detailed descriptions on how to implement global Token validation using interceptors and filters, and provides complete code examples and best practices.
1. Why do global Token verification be needed?
In a front-end and back-end separation architecture, clients are usually authenticated through tokens. If each interface is verified separately, the following problems can be caused:
- Code redundancy: Each interface needs to write duplicate verification logic.
- Difficulty in maintenance: When the verification logic needs to be modified, all relevant interfaces need to be modified.
- Easy to miss: When adding new interfaces, you may forget to add verification logic, resulting in security vulnerabilities.
Through global token verification, the verification logic of all interfaces can be handled uniformly, improving the reusability and maintainability of the code.
2. Use interceptor to implement global Token verification
Interceptors are a mechanism provided by Spring MVC that allows specific logic to be executed before or after the request reaches the controller. Here are the implementation steps:
1. Create a Token Verification Interceptor
Create an interceptor class to implementHandlerInterceptor
Interface, and inpreHandle
Write Token verification logic in the method.
import ; import ; import ; import ; @Component public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Get the token from the request header String token = ("Authorization"); // Verify Token if (token == null || !isValidToken(token)) { (HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized ().write("Token is invalid or not provided"); return false; // Interrupt request } return true; // Continue to execute the request } // Simulate Token verification logic private boolean isValidToken(String token) { // Here you can call the specific Token verification service return "valid-token".equals(token); } }
2. Register the interceptor
Register the interceptor into Spring MVC and configure the paths to be intercepted.
import ; import ; import ; import ; @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private TokenInterceptor tokenInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // Intercept all paths (tokenInterceptor) .addPathPatterns("/**") // Intercept all interfaces .excludePathPatterns("/login", "/register"); // Exclude paths that do not need to be intercepted } }
3. Test the interceptor
After starting the project, when accessing any interface, if no valid token is provided in the request header, a 401 error will be returned.
3. Use filters to implement global Token verification
Filters are a mechanism provided by Servlets that execute logic before requests arrive in Spring MVC. Here are the implementation steps:
1. Create a Token Verification Filter
Create a filter class to implementFilter
Interface, and indoFilter
Write Token verification logic in the method.
import .*; import ; import ; import ; public class TokenFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // Get the token from the request header String token = ("Authorization"); // Verify Token if (token == null || !isValidToken(token)) { (HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized ().write("Token is invalid or not provided"); return; // Interrupt request } (request, response); // Continue to execute the request } // Simulate Token verification logic private boolean isValidToken(String token) { // Here you can call the specific Token verification service return "valid-token".equals(token); } }
2. Register filters
Register the filter into Spring Boot and configure the paths to be intercepted.
import ; import ; import ; @Configuration public class FilterConfig { @Bean public FilterRegistrationBean<TokenFilter> tokenFilter() { FilterRegistrationBean<TokenFilter> registrationBean = new FilterRegistrationBean<>(); (new TokenFilter()); ("/*"); // Intercept all paths (1); // Set filter order return registrationBean; } }
3. Test the filter
After starting the project, when accessing any interface, if no valid token is provided in the request header, a 401 error will be returned.
4. Interceptor vs filter
1. Advantages of Interceptors
- Deeply integrated with Spring MVC, you can access Spring's context and beans.
- The paths intercepted can be accurately controlled (through
addPathPatterns
andexcludePathPatterns
)。 - Suitable for handling interceptions related to business logic (such as permission verification, logging).
2. Advantages of filters
- In the lower level, all requests (including static resources) can be intercepted.
- Suitable for handling Servlet-related logic (such as encoding settings, cross-domain processing).
3. Select suggestions
- If you need to process logic (such as dependency injection) in the context of Spring MVC, use interceptors first.
- If you need to intercept all requests (including static resources), or if you need to have a lower level of control, use filters first.
5. Global exception handling
In an interceptor or filter, if verification fails, returning an error response directly may cause the client to be unable to resolve. The error information in JSON format can be returned uniformly through the global exception handling mechanism.
1. Define a unified response format
public class ApiResponse { private boolean status; private int code; private String message; // Constructor method and Getter/Setter omit}
2. Global exception handler
import ; import ; import ; import ; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler() @ResponseStatus() public ApiResponse handleUnauthorizedException(UnauthorizedException e) { return new ApiResponse(false, 401, ()); } }
3. Throw an exception in the interceptor or filter
if (token == null || !isValidToken(token)) { throw new UnauthorizedException("Token is invalid or not provided"); }
6. Summary
Interceptors or filters make it easy to verify tokens for all interfaces in Spring Boot projects. Here is a comparison of the two methods:
characteristic | Interceptor | Filter |
---|---|---|
Integration method | Spring MVC Integration | Servlet Integration |
Intercept range | Only intercept Spring MVC requests | All requests can be intercepted (including static resources) |
Dependency injection | support | Not supported |
Applicable scenarios | Interception related to business logic (such as permission verification) | Intercepting related to underlying logic (such as encoding settings) |
Selecting the appropriate method according to project needs and combining the global exception handling mechanism can build a robust and easy-to-maintain Token verification system.
This is the end of this article about the implementation of two ways of global token verification in Spring Boot. For more related content on Spring Boot global token verification, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!