A JWT validation filter checks if a user's token is valid before allowing access to protected parts of a web app. It helps keep the app safe by making sure only authorized users can get in.
JWT validation filter in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
public class JwtValidationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = extractToken(request); if (token != null && validateToken(token)) { // Set authentication in security context filterChain.doFilter(request, response); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } private String extractToken(HttpServletRequest request) { String bearer = request.getHeader("Authorization"); if (bearer != null && bearer.startsWith("Bearer ")) { return bearer.substring(7); } return null; } private boolean validateToken(String token) { // Logic to check token signature and expiry return true; // or false } }
The filter extends OncePerRequestFilter to run once per request.
Extract the token from the Authorization header, usually starting with "Bearer ".
String token = extractToken(request); if (token != null && validateToken(token)) { // Allow access } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; }
private String extractToken(HttpServletRequest request) {
String bearer = request.getHeader("Authorization");
if (bearer != null && bearer.startsWith("Bearer ")) {
return bearer.substring(7);
}
return null;
}private boolean validateToken(String token) {
// Use JWT library to check signature and expiry
return true; // or false
}This filter checks the Authorization header for a JWT token. If the token equals "valid-token", it lets the request continue. Otherwise, it sends a 401 Unauthorized response with a message.
package com.example.security; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; public class JwtValidationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = extractToken(request); if (token != null && validateToken(token)) { // Token is valid, continue processing filterChain.doFilter(request, response); } else { // Token missing or invalid, reject request response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("Unauthorized: Invalid or missing token"); } } private String extractToken(HttpServletRequest request) { String bearer = request.getHeader("Authorization"); if (bearer != null && bearer.startsWith("Bearer ")) { return bearer.substring(7); } return null; } private boolean validateToken(String token) { // Simple dummy validation: token must equal "valid-token" for demo return "valid-token".equals(token); } }
Always place the JWT validation filter before your controllers in the filter chain.
Use a real JWT library like jjwt or java-jwt to verify token signature and expiry.
Make sure to handle exceptions and send clear error messages for better debugging.
A JWT validation filter checks tokens on incoming requests to protect your app.
It extracts the token from the Authorization header and verifies it.
If the token is valid, the request proceeds; if not, it returns 401 Unauthorized.
Practice
Solution
Step 1: Understand JWT validation filter role
A JWT validation filter is designed to intercept incoming requests and check the validity of JWT tokens.Step 2: Identify the correct purpose
It does not generate tokens or encrypt data; its main job is to verify tokens to allow or deny access.Final Answer:
To check and verify JWT tokens on incoming HTTP requests -> Option BQuick Check:
JWT validation filter = Verify tokens [OK]
- Confusing validation with token generation
- Thinking filter encrypts data
- Assuming it only logs requests
Solution
Step 1: Identify filter method for request processing
In Spring Boot, filters extend OncePerRequestFilter and override doFilterInternal to process requests.Step 2: Match method to JWT validation
doFilterInternal is where JWT token extraction and validation happen before continuing the chain.Final Answer:
doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) -> Option AQuick Check:
JWT validation code goes in doFilterInternal [OK]
- Using init() which is for filter setup only
- Confusing destroy() with request handling
- Inventing non-existent handleRequest() method
String token = request.getHeader("Authorization");
if (token == null || !jwtUtil.validateToken(token)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
chain.doFilter(request, response);Solution
Step 1: Analyze token check condition
If token is missing or invalid, the code sets response status to 401 and returns immediately.Step 2: Understand filter chain behavior
Because it returns before calling chain.doFilter, the request does not proceed further.Final Answer:
The request is blocked with 401 Unauthorized status -> Option CQuick Check:
Invalid token = 401 block [OK]
- Assuming request proceeds despite invalid token
- Expecting automatic token refresh
- Thinking NullPointerException occurs here
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = request.getHeader("Authorization");
if (token != null && jwtUtil.validateToken(token)) {
SecurityContextHolder.getContext().setAuthentication(jwtUtil.getAuthentication(token));
}
chain.doFilter(request, response);
}Solution
Step 1: Review token validation logic
The code sets authentication only if token is valid, but does not block invalid or missing tokens.Step 2: Check filter chain continuation
It always calls chain.doFilter, so invalid requests proceed without rejection.Final Answer:
It does not handle the case when token is missing or invalid by blocking the request -> Option AQuick Check:
Missing block on invalid token = security hole [OK]
- Allowing requests without token validation
- Calling chain.doFilter twice (not here though)
- Misunderstanding exception handling in filters
doFilterInternal?Solution
Step 1: Determine correct order of JWT processing
First, extract the token from the Authorization header, then validate it to ensure it's correct.Step 2: Set authentication and control flow
If valid, set user authentication in the security context, then continue the filter chain; otherwise, respond with 401 Unauthorized.Final Answer:
Extract token -> Validate token -> Set authentication -> Continue filter chain -> Else respond 401 -> Option DQuick Check:
Correct JWT filter flow = Extract token -> Validate token -> Set authentication -> Continue filter chain -> Else respond 401 [OK]
- Validating before extracting token
- Setting authentication before validation
- Continuing filter chain before validation
