java
39 lines · 8 steps
How a JWT auth filter works in Spring
A once-per-request filter that reads a bearer token, validates it, and populates Spring Security's context.
Explained by
highlit
1@Component
2public class JwtAuthenticationFilter extends OncePerRequestFilter {
3
4 private final JwtTokenProvider tokenProvider;
5 private final UserDetailsService userDetailsService;
6
7 public JwtAuthenticationFilter(JwtTokenProvider tokenProvider, UserDetailsService userDetailsService) {
8 this.tokenProvider = tokenProvider;
9 this.userDetailsService = userDetailsService;
10 }
11
12 @Override
13 protected void doFilterInternal(HttpServletRequest request,
14 HttpServletResponse response,
15 FilterChain filterChain) throws ServletException, IOException {
16 String token = resolveToken(request);
17
18 if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
19 String username = tokenProvider.getUsername(token);
20 UserDetails userDetails = userDetailsService.loadUserByUsername(username);
21
22 UsernamePasswordAuthenticationToken authentication =
23 new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
24 authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
25
26 SecurityContextHolder.getContext().setAuthentication(authentication);
27 }
28
29 filterChain.doFilter(request, response);
30 }
31
32 private String resolveToken(HttpServletRequest request) {
33 String header = request.getHeader(HttpHeaders.AUTHORIZATION);
34 if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
35 return header.substring(7);
36 }
37 return null;
38 }
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Extending OncePerRequestFilter guarantees the auth logic runs exactly once per request, even across forwards.
- 2Stateless JWT auth works by reconstructing an Authentication from the token rather than a server session.
- 3Setting the Authentication on SecurityContextHolder is what makes the request count as authenticated downstream.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-jwt-auth-filter-works-in-spring-explained-java-3df9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.