Bird
Raised Fist0
Spring Bootframework~10 mins

JWT validation filter in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - JWT validation filter
Incoming HTTP Request
JWT Validation Filter
JWT Valid?
Set User Auth
Continue Filter Chain
Controller
The filter intercepts each HTTP request, checks the JWT token, and either sets user authentication or rejects the request before passing control.
Execution Sample
Spring Boot
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  String token = extractToken((HttpServletRequest) req);
  if (validateToken(token)) {
    setAuthentication(token);
    chain.doFilter(req, res);
  } else {
    rejectRequest((HttpServletResponse) res);
  }
}
This filter extracts a JWT token, validates it, sets authentication if valid, or rejects the request if invalid.
Execution Table
StepActionToken ExtractedToken Valid?Authentication SetFilter Chain CalledResponse Status
1Extract token from headereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...N/ANoNoN/A
2Validate tokeneyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...YesNoNoN/A
3Set authentication in security contexteyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...YesYesNoN/A
4Call next filter in chaineyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...YesYesYesN/A
5Request proceeds to controllereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...YesYesYes200 OK
6If token invalid, reject requestinvalid.token.valueNoNoNo401 Unauthorized
💡 Execution stops when token is invalid and request is rejected with 401, or continues if token is valid.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
tokennulleyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
isValidfalsefalsetruetruetrue
authenticationSetfalsefalsefalsetruetrue
responseStatusnullnullnullnull200 OK or 401 Unauthorized
Key Moments - 2 Insights
Why does the filter reject the request immediately when the token is invalid?
Because the execution_table row 6 shows that when token validation fails, the filter does not call the next filter and sends a 401 response to stop unauthorized access.
When is the authentication set in the security context?
As shown in execution_table row 3, authentication is set only after the token is validated successfully, ensuring only valid users proceed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response status when the token is valid?
A401 Unauthorized
B200 OK
C500 Internal Server Error
DNo response sent yet
💡 Hint
Check the last row where token is valid and the response status column.
At which step does the filter call the next filter in the chain?
AStep 4
BStep 6
CStep 2
DStep 1
💡 Hint
Look at the 'Filter Chain Called' column in the execution_table.
If the token is invalid, what happens to the authenticationSet variable?
AIt becomes null
BIt becomes true
CIt remains false
DIt throws an error
💡 Hint
Refer to variable_tracker row for authenticationSet and execution_table row 6.
Concept Snapshot
JWT Validation Filter in Spring Boot:
- Intercepts HTTP requests
- Extracts JWT token from Authorization header
- Validates token signature and expiry
- If valid, sets user authentication in security context
- If invalid, rejects request with 401 Unauthorized
- Passes control to next filter or controller
- Ensures secure access to protected endpoints
Full Transcript
A JWT validation filter in Spring Boot intercepts incoming HTTP requests to check the JWT token in the Authorization header. It extracts the token, validates it for correctness and expiry, and if valid, sets the user authentication in the security context. This allows the request to continue to the next filter or controller. If the token is invalid, the filter immediately rejects the request by sending a 401 Unauthorized response, preventing access to protected resources. This process ensures only authenticated users can access secured endpoints.

Practice

(1/5)
1. What is the main purpose of a JWT validation filter in a Spring Boot application?
easy
A. To generate new JWT tokens for users
B. To check and verify JWT tokens on incoming HTTP requests
C. To log all incoming requests without validation
D. To encrypt the response data before sending

Solution

  1. Step 1: Understand JWT validation filter role

    A JWT validation filter is designed to intercept incoming requests and check the validity of JWT tokens.
  2. 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.
  3. Final Answer:

    To check and verify JWT tokens on incoming HTTP requests -> Option B
  4. Quick Check:

    JWT validation filter = Verify tokens [OK]
Hint: JWT filter checks tokens on requests, not generating or logging [OK]
Common Mistakes:
  • Confusing validation with token generation
  • Thinking filter encrypts data
  • Assuming it only logs requests
2. Which method in a Spring Boot filter is typically overridden to implement JWT validation logic?
easy
A. doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
B. init(FilterConfig filterConfig)
C. destroy()
D. handleRequest(HttpRequest request)

Solution

  1. Step 1: Identify filter method for request processing

    In Spring Boot, filters extend OncePerRequestFilter and override doFilterInternal to process requests.
  2. Step 2: Match method to JWT validation

    doFilterInternal is where JWT token extraction and validation happen before continuing the chain.
  3. Final Answer:

    doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) -> Option A
  4. Quick Check:

    JWT validation code goes in doFilterInternal [OK]
Hint: JWT validation logic goes in doFilterInternal method [OK]
Common Mistakes:
  • Using init() which is for filter setup only
  • Confusing destroy() with request handling
  • Inventing non-existent handleRequest() method
3. Given this snippet inside a JWT validation filter, what happens if the token is invalid?
String token = request.getHeader("Authorization");
if (token == null || !jwtUtil.validateToken(token)) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return;
}
chain.doFilter(request, response);
medium
A. The server throws a NullPointerException
B. The request proceeds without validation
C. The request is blocked with 401 Unauthorized status
D. The token is refreshed automatically

Solution

  1. Step 1: Analyze token check condition

    If token is missing or invalid, the code sets response status to 401 and returns immediately.
  2. Step 2: Understand filter chain behavior

    Because it returns before calling chain.doFilter, the request does not proceed further.
  3. Final Answer:

    The request is blocked with 401 Unauthorized status -> Option C
  4. Quick Check:

    Invalid token = 401 block [OK]
Hint: Invalid token triggers 401 and stops request chain [OK]
Common Mistakes:
  • Assuming request proceeds despite invalid token
  • Expecting automatic token refresh
  • Thinking NullPointerException occurs here
4. Identify the error in this JWT validation filter snippet:
@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);
}
medium
A. It does not handle the case when token is missing or invalid by blocking the request
B. It incorrectly sets authentication before validation
C. It calls chain.doFilter twice causing errors
D. It throws IOException without handling

Solution

  1. Step 1: Review token validation logic

    The code sets authentication only if token is valid, but does not block invalid or missing tokens.
  2. Step 2: Check filter chain continuation

    It always calls chain.doFilter, so invalid requests proceed without rejection.
  3. Final Answer:

    It does not handle the case when token is missing or invalid by blocking the request -> Option A
  4. Quick Check:

    Missing block on invalid token = security hole [OK]
Hint: Always block requests with missing or invalid tokens [OK]
Common Mistakes:
  • Allowing requests without token validation
  • Calling chain.doFilter twice (not here though)
  • Misunderstanding exception handling in filters
5. You want to create a JWT validation filter that extracts the token from the Authorization header, validates it, and sets the user authentication in the security context only if valid. Which sequence of actions is correct inside doFilterInternal?
hard
A. Continue filter chain -> Extract token -> Validate token -> Set authentication -> Else respond 401
B. Validate token -> Extract token -> Set authentication -> Continue filter chain -> Else respond 401
C. Set authentication -> Extract token -> Validate token -> Continue filter chain -> Else respond 401
D. Extract token -> Validate token -> Set authentication -> Continue filter chain -> Else respond 401

Solution

  1. Step 1: Determine correct order of JWT processing

    First, extract the token from the Authorization header, then validate it to ensure it's correct.
  2. 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.
  3. Final Answer:

    Extract token -> Validate token -> Set authentication -> Continue filter chain -> Else respond 401 -> Option D
  4. Quick Check:

    Correct JWT filter flow = Extract token -> Validate token -> Set authentication -> Continue filter chain -> Else respond 401 [OK]
Hint: Extract first, then validate, set auth, continue or block [OK]
Common Mistakes:
  • Validating before extracting token
  • Setting authentication before validation
  • Continuing filter chain before validation