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
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 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.