Authentication Interceptor
Overview
Envrionment Details:
- Spring Boot: 3.1.3
- Java: 17
An interceptor in Spring MVC allows interception of incoming requests to execute custom logic either before or after the handler processes the request. An authentication interceptor typically verifies whether a user is logged in; if not, it redirects them to the login page.
Implementation Steps
Step 1: Define the Interceptor
Bellow is the implementation of the LoginInterceptor:
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Retrieve the Authorization header from the request
String authHeader = request.getHeader("Authorization");
try {
// Parse and validate the JWT token
Map<String, Object> payload = JwtUtil.parseToken(authHeader);
// Proceed with the request if valid
return true;
} catch (Exception e) {
// Deny access if validation fails
response.setStatus(401);
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Executed after handler processing but before view rendering
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Executed after the complete request handling cycle
}
}
Step 2: Register the Interceptor
The following configuration registers the interceptor with the application:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Exclude login and registration endpoints from interception
registry.addInterceptor(interceptor)
.excludePathPatterns("/user/login", "/user/register");
}
}
Summary
The core functionality resides in the preHandle method. It extracts the "Authorization" header which typically holds a JWT token. Using JwtUtil.parseToken, it validates the token's authenticity. A successful validation results in returning true, allowing the request to proceed. Otherwise, it sets an HTTP 401 status code and returns false to block the request.
This interceptor must be registered within the Spring MVC framework using a configuration class.