<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muni Kiran Narpareddi on Medium]]></title>
        <description><![CDATA[Stories by Muni Kiran Narpareddi on Medium]]></description>
        <link>https://medium.com/@narmuni123?source=rss-241c181bb7f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kgI2R6loLdi2U20A</url>
            <title>Stories by Muni Kiran Narpareddi on Medium</title>
            <link>https://medium.com/@narmuni123?source=rss-241c181bb7f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:49:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@narmuni123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Securing Your Spring Boot Application with JWT Authentication: A Practical Guide]]></title>
            <link>https://medium.com/@narmuni123/securing-your-spring-boot-application-with-jwt-authentication-a-practical-guide-1b8d624405f3?source=rss-241c181bb7f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8d624405f3</guid>
            <dc:creator><![CDATA[Muni Kiran Narpareddi]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 02:32:17 GMT</pubDate>
            <atom:updated>2025-07-28T02:32:17.247Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Security is a crucial aspect of developing modern web and mobile applications. With RESTful APIs becoming the backbone of most applications, safeguarding endpoints using robust authentication mechanisms is more important than ever. One of the most prevalent patterns in Java Spring ecosystems is JWT (JSON Web Token)–based authentication. In this article, I’ll walk you through implementing JWT-based authentication in a Spring Boot application, using a real-world example from an online delivery service project.</p><h3>Why JWT?</h3><p>JWT is a self-contained token format that allows you to transfer information securely between parties as a JSON object. Its stateless nature means no session is maintained on the server, improving scalability and simplifying API management, especially for microservices and distributed systems.</p><h3>Understanding the Building Blocks</h3><p>The core of our authentication system revolves around the following components:</p><ol><li>CustomUserDetailsService — Responsible for loading user-specific data.</li><li>JwtUtil — Handles creation and validation of JWT tokens.</li><li>JwtAuthFilter — Intercepts HTTP requests to enforce authentication.</li><li>SecurityConfig — Configures Spring Security to apply JWT logic.</li></ol><p>Let’s break down these components and see how they fit together.</p><h3>1. User Authentication with CustomUserDetailsService</h3><p>The service CustomUserDetailsService implements Spring Security’s UserDetailsService. Its primary role is to fetch user details from the database using the username (or email).</p><pre>@Override<br>public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>    User user = userRepository.findByUsername(username)<br>            .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;User not found&quot;));<br><br>    return new org.springframework.security.core.userdetails.User(<br>            user.getUsername(),<br>            user.getPassword(),<br>            Collections.singleton(new SimpleGrantedAuthority(&quot;ROLE_&quot; + user.getRole().name()))<br>    );<br>}</pre><p><strong>Key Takeaways</strong>:</p><ul><li>Loads user information from your database.</li><li>Converts user entity to a Spring Security-friendly UserDetails object.</li><li>Assigns roles (authorities) which allow for role-based access control.</li></ul><h3>2. Generating and Validating Tokens: JwtUtil</h3><p>JwtUtil is a utility class dedicated to all things JWT—generating tokens during login and verifying tokens on subsequent requests.</p><pre>public String generateToken(String username) {<br>    return Jwts.builder()<br>            .setSubject(username)<br>            .setIssuedAt(new Date())<br>            .setExpiration(new Date(System.currentTimeMillis() + expiration))<br>            .signWith(key)<br>            .compact();<br>}</pre><p>Highlights:</p><ul><li>Sets the subject (username) and expiration.</li><li>Signs the token to ensure it hasn’t been tampered with.</li></ul><p>Token validation and extraction are handled similarly, providing assurance that only valid, non-expired tokens are accepted.</p><h3>3. Authenticating Requests: JwtAuthFilter</h3><p>The JwtAuthFilter extends OncePerRequestFilter, meaning it intercepts every HTTP request once per request cycle.</p><pre>@Override<br>protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)<br>        throws ServletException, IOException {<br><br>    String path = request.getServletPath();<br><br>    // Bypass JWT validation for public endpoints (e.g., /api/v1/auth/**)<br>    if (path.startsWith(&quot;/api/v1/auth/&quot;)) {<br>        filterChain.doFilter(request, response);<br>        return;<br>    }<br><br>    String authHeader = request.getHeader(&quot;Authorization&quot;);<br>    if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>        filterChain.doFilter(request, response);<br>        return;<br>    }<br><br>    String token = authHeader.substring(7);<br>    String username = jwtUtil.extractUsername(token);<br><br>    if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>        UserDetails userDetails = userDetailsService.loadUserByUsername(username);<br><br>        if (jwtUtil.isTokenValid(token)) {<br>            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(<br>                    userDetails, null, userDetails.getAuthorities()<br>            );<br>            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>            SecurityContextHolder.getContext().setAuthentication(authToken);<br>        }<br>    }<br><br>    filterChain.doFilter(request, response);<br>}</pre><p>Key Functions:</p><ul><li>Skips public authentication routes (e.g., /api/v1/auth/**).</li><li>Extracts and validates the JWT from the Authorization HTTP header.</li><li>Sets authentication details in the Spring Security context, enabling authorization at subsequent layers.</li></ul><h3>4. Bringing it Together: SecurityConfig</h3><p>Finally, the SecurityConfig configures Spring Security to use our custom logic.</p><pre>@Bean<br>public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>    return http.csrf(csrf -&gt; csrf.disable())<br>            .authorizeHttpRequests(auth -&gt; auth<br>                    .requestMatchers(&quot;/api/v1/auth/**&quot;).permitAll()<br>                    .anyRequest().authenticated()<br>            )<br>            .userDetailsService(userDetailsService)<br>            .sessionManagement(sess -&gt; sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br>            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)<br>            .build();<br>}</pre><p>What’s happening:</p><ul><li>CSRF protection is disabled (token-based authentication is immune to CSRF by design).</li><li>Public endpoints are whitelisted.</li><li>All other endpoints require authentication.</li><li>Sessions are stateless, befitting JWT.</li><li>The custom JWT filter is plugged into the processing pipeline.</li></ul><h3>Conclusion</h3><p>By combining these classes and configurations, you establish a secure, stateless authentication system in your Spring Boot application. Users authenticate once to receive a JWT, which accompanies their subsequent requests, ensuring that only authenticated users gain access to protected resources.</p><p>Benefits of this approach:</p><ul><li>Scalable — statelessness means easy horizontal scaling.</li><li>Flexible — easy to expand to incorporate roles/permissions.</li><li>Secure — cryptographically signed tokens prevent tampering.</li></ul><p>If you’re building APIs or modern web apps with Spring Boot, leveraging JWT authentication is a must for both security and scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8d624405f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>