What is Spring Boot JWT authentication implementation?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
Implementing JWT authentication in Spring Boot: Dependencies: spring-boot-starter-security + io.jsonwebtoken:jjwt-api, jjwt-impl, jjwt-jackson. JWT utility class: @Component public class JwtUtil { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration:86400}") private Long expiration; public String generateToken(UserDetails userDetails) { return Jwts.builder().setSubject(userDetails.getUsername()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)).signWith(getSignKey()).compact(); } public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } public boolean validateToken(String token, UserDetails userDetails) { return extractUsername(token).equals(userDetails.getUsername()) && !isTokenExpired(token); } private Key getSignKey() { return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)); } }. JWT filter: @Component public class JwtAuthFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { String header = req.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { String token = header.substring(7); String username = jwtUtil.extractUsername(token); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails user = userDetailsService.loadUserByUsername(username); if (jwtUtil.validateToken(token, user)) { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); } } } chain.doFilter(req, resp); } }. Register filter in SecurityFilterChain: .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class). Login endpoint: authenticate with AuthenticationManager, generate and return JWT token.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Spring Boot project.