How do you implement JWT authentication in Spring Boot? स्प्रिंग बूट में JWT ऑथेंटिकेशन कैसे इम्प्लीमेंट करें?
JWT (JSON Web Token) authentication is stateless: after a user logs in with credentials, the server generates a signed token containing claims (user id, roles, expiry) and returns it to the client, which sends it in the Authorization: Bearer <token> header on every subsequent request.
A custom OncePerRequestFilter is added to the filter chain to extract and validate the token on each request, parse its claims, and populate the SecurityContext if valid, without needing a server-side session — making JWT well suited for stateless REST APIs and microservices.
public class JwtAuthFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
String token = extractToken(req);
if (token != null && jwtUtil.validateToken(token)) {
UsernamePasswordAuthenticationToken auth = jwtUtil.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(req, res);
}
}JWT (JSON Web Token) ऑथेंटिकेशन स्टेटलेस होता है: यूज़र के क्रेडेंशियल्स से लॉगिन करने के बाद, सर्वर क्लेम्स (यूज़र आईडी, रोल्स, एक्सपायरी) वाला एक साइन्ड टोकन जनरेट करता है और क्लाइंट को लौटाता है, जो इसे हर बाद की रिक्वेस्ट में Authorization: Bearer <token> हेडर में भेजता है।
हर रिक्वेस्ट पर टोकन को एक्सट्रैक्ट और वैलिडेट करने के लिए फ़िल्टर चेन में एक कस्टम OncePerRequestFilter जोड़ा जाता है, जो इसके क्लेम्स पार्स करता है और वैध होने पर SecurityContext भरता है — बिना सर्वर-साइड सेशन की ज़रूरत के।
public class JwtAuthFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
String token = extractToken(req);
if (token != null && jwtUtil.validateToken(token)) {
UsernamePasswordAuthenticationToken auth = jwtUtil.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(req, res);
}
}Was this answer clear?