<?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 Shivam  on Medium]]></title>
        <description><![CDATA[Stories by Shivam  on Medium]]></description>
        <link>https://medium.com/@shivam.72329?source=rss-c5e4400b9cde------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VXnLFKau0B8-MqMq</url>
            <title>Stories by Shivam  on Medium</title>
            <link>https://medium.com/@shivam.72329?source=rss-c5e4400b9cde------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:16:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivam.72329/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[Login, Signup, Logout, JWT, Refresh Tokens — Explained Like You’re a Developer]]></title>
            <link>https://medium.com/@shivam.72329/login-signup-logout-jwt-refresh-tokens-explained-like-youre-a-developer-b79b621d903b?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79b621d903b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 17:03:02 GMT</pubDate>
            <atom:updated>2026-01-11T17:23:49.070Z</atom:updated>
            <content:encoded><![CDATA[<h3>Login, Signup, Logout, JWT, Refresh Tokens — Explained Like You’re a Developer <a href="https://medium.com/p/1b51fd4753e5?source=post_stats_page--------------------------------------------">🚀</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2OmeN50XcxFf_yU" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Stop using LocalStorage for everything. Here is the secure way to handle Logins, Access Tokens, and Refresh Tokens.</h3><p><strong>Author:</strong> <em>Shivam Chaturvedi</em></p><p>We have all been there. You are building your first Full Stack app. You build a Login form, you get a token back, and you stuff it into localStorage. You pat yourself on the back and move on.</p><p><strong>But wait.</strong> If a hacker manages to run a simple script on your site (XSS attack), they can read everything in LocalStorage. They steal your token. They become you.</p><p>Today, we are going to build an <strong>“Industrial Grade”</strong> Authentication system. This is the same architecture used by major tech companies. It’s secure, it’s robust, and it keeps your users logged in without compromising safety.</p><p>In this guide, we will build a full <strong>MERN Stack</strong> (MongoDB, Express, React, Node) auth system.</p><h3>🧠 The Concept: The Office Building Analogy</h3><p>Before we write code, let’s understand the strategy. Most beginners get confused between <strong>Authentication</strong> (Who are you?) and <strong>Authorization</strong> (What can you do?).</p><p>Think of your App as a high-security <strong>Office Building</strong>.</p><h3>1. The Access Token (The Visitor Badge)</h3><ul><li><strong>What is it?</strong> A plastic badge you wear on your shirt.</li><li><strong>How long does it last?</strong> 15 minutes.</li><li><strong>What does it do?</strong> It opens doors (API endpoints).</li><li><strong>Security:</strong> If you lose it, the thief can only use it for 15 minutes before it stops working.</li></ul><h3>2. The Refresh Token (The Renewal Ticket)</h3><ul><li><strong>What is it?</strong> A special secure ticket you keep hidden in your pocket.</li><li><strong>How long does it last?</strong> 7 Days.</li><li><strong>What does it do?</strong> It opens <strong>NO</strong> doors. It is only used to go to the Front Desk to get a <em>new</em> Visitor Badge.</li><li><strong>Security:</strong> We store this in a <strong>HttpOnly Cookie</strong>. This means JavaScript cannot touch it. Even if a hacker runs a script on your browser, they cannot read this cookie.</li></ul><h3>🛠 Phase 1: The Backend (Node.js &amp; Express)</h3><p>Let’s build the “Badge Printer” (The Server).</p><h3>Step 1: Dependencies</h3><p>You need a few key tools. Run this in your app directory where package.json file exist…</p><p>npm install express mongoose jsonwebtoken bcryptjs cors cookie-parser dotenv</p><ul><li><strong>jsonwebtoken:</strong> To create the badges.</li><li><strong>cookie-parser:</strong> To read the secure cookie.</li><li><strong>cors:</strong> To allow the frontend to talk to us.</li></ul><h3>Step 2: The User Model</h3><p>We need to update our database schema. Notice we are storing the refreshToken. This allows us to revoke access (ban a user) by deleting this field from the database.</p><pre>// models/User.js<br>const mongoose = require(&#39;mongoose&#39;);<br>const userSchema = new mongoose.Schema({<br>  username: { type: String, required: true, unique: true },<br>  email:    { type: String, required: true, unique: true },<br>  password: { type: String, required: true },<br>  refreshToken: { type: String } // Crucial for security control<br>});<br>module.exports = mongoose.model(&#39;User&#39;, userSchema);</pre><h3>Step 3: The Login Route (The Magic)</h3><p>This is where we split the tokens. One goes to the Body (JSON), the other goes to the Cookie.</p><pre>// routes/authRoutes.js<br>router.post(&#39;/login&#39;, async (req, res) =&gt; {<br>  const { email, password } = req.body;<br>  <br>  // 1. Validate User &amp; Password (bcrypt)<br>  const user = await User.findOne({ email });<br>  if (!user || !await bcrypt.compare(password, user.password)) {<br>      return res.status(400).json({ message: &quot;Invalid credentials&quot; });<br>  }<br>  // 2. Generate Tokens<br>  const accessToken = jwt.sign({ id: user._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: &#39;15m&#39; });<br>  const refreshToken = jwt.sign({ id: user._id }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: &#39;7d&#39; });<br>  // 3. Save Refresh Token to DB (For revocation capability)<br>  user.refreshToken = refreshToken;<br>  await user.save();<br>// 4. Send Refresh Token in HTTP-ONLY Cookie<br>  res.cookie(&#39;jwt&#39;, refreshToken, {<br>    httpOnly: true, // JS cannot access this<br>    secure: true,   // HTTPS only<br>    sameSite: &#39;None&#39;, <br>    maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days<br>  });<br>  // 5. Send Access Token in JSON<br>  res.json({ accessToken });<br>});</pre><h3>Step 4: The Refresh Route</h3><p>This is the “Silent” route. The frontend calls this when the short-term badge expires.</p><pre>router.get(&#39;/refresh&#39;, async (req, res) =&gt; {<br>  const cookies = req.cookies;<br>  if (!cookies?.jwt) return res.sendStatus(401); // No cookie? Bye.<br>const refreshToken = cookies.jwt;<br>  const user = await User.findOne({ refreshToken });<br>  // Token reuse detection: If cookie exists but not in DB, it&#39;s a hacked token!<br>  if (!user) return res.sendStatus(403); <br>  jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, decoded) =&gt; {<br>    if (err || user.id !== decoded.id) return res.sendStatus(403);<br>    <br>    // Issue NEW Access Token<br>    const accessToken = jwt.sign({ id: user._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: &#39;15m&#39; });<br>    res.json({ accessToken });<br>  });<br>});</pre><h3>Phase 2: The Frontend (React + Axios)</h3><p>Now for the cool part. How do we make the user stay logged in automatically?</p><p>We use an <strong>Axios Interceptor</strong>. Think of this as a “Personal Assistant” that sits between your React components and the Server.</p><h3>The Interceptor Logic</h3><ol><li><strong>Request:</strong> Always attach the Access Token from memory/localStorage.</li><li><strong>Response Error:</strong> If the server says “403 Forbidden” (Token Expired)…</li><li><strong>The Fix:</strong> The Assistant pauses the request, goes to the /refresh endpoint, gets a new token, and <em>retries</em> the original request.</li><li><strong>Result:</strong> The user never knows an error happened.</li></ol><h3>The Code (api/axios.js)</h3><pre>import axios from &#39;axios&#39;;<br>const api = axios.create({<br>  baseURL: &#39;http://localhost:4000&#39;,<br>  withCredentials: true // VITAL: Allows cookies to be sent/received<br>});<br>// 1. Request Interceptor: Attach the badge<br>api.interceptors.request.use(<br>  (config) =&gt; {<br>    const token = localStorage.getItem(&#39;accessToken&#39;);<br>    if (token) config.headers[&#39;Authorization&#39;] = `Bearer ${token}`;<br>    return config;<br>  },<br>  (error) =&gt; Promise.reject(error)<br>);<br><br>// 2. Response Interceptor: Handle the expiration<br>api.interceptors.response.use(<br>  (response) =&gt; response,<br>  async (error) =&gt; {<br>    const originalRequest = error.config;<br>    // If error is 403 and we haven&#39;t retried yet...<br>    if (error.response?.status === 403 &amp;&amp; !originalRequest._retry) {<br>      originalRequest._retry = true; // Mark to prevent infinite loops<br>      try {<br>        // A. Call the refresh endpoint (Cookie is sent automatically)<br>        const response = await api.get(&#39;/auth/refresh&#39;);<br>        <br>        // B. Save new token<br>        const newAccessToken = response.data.accessToken;<br>        localStorage.setItem(&#39;accessToken&#39;, newAccessToken);<br>        // C. Update header and retry original request<br>        originalRequest.headers[&#39;Authorization&#39;] = `Bearer ${newAccessToken}`;<br>        return api(originalRequest);<br>        <br>      } catch (err) {<br>        // D. If refresh fails, user is truly logged out<br>        window.location.href = &#39;/login&#39;;<br>      }<br>    }<br>    return Promise.reject(error);<br>  }<br>);<br>export default api;</pre><h3>Putting It All Together</h3><p>When you run this system, here is the lifecycle of a user session:</p><ol><li><strong>User Logs In:</strong> Server sends a short-lived token (JSON) and a long-lived cookie.</li><li><strong>User Browses:</strong> React sends the short token in headers. All good.</li><li><strong>15 Minutes Later:</strong> The short token dies.</li><li><strong>User Clicks a Button:</strong> The API returns 403 Error.</li><li><strong>Auto-Magic:</strong> The Interceptor catches the 403, hits /refresh using the hidden cookie, gets a fresh token, and retries the click.</li><li><strong>User Experience:</strong> Seamless. No “Session Expired” modals. No forced logouts.</li></ol><h3>Why go through all this trouble?</h3><ul><li><strong>XSS Protection:</strong> Sensitive Refresh Tokens are not accessible via JavaScript.</li><li><strong>Revocation:</strong> You can ban a user instantly by deleting their token from the database.</li><li><strong>UX:</strong> Best of both worlds — secure like a bank, smooth like a social media app.</li></ul><h3>Final Tip for Developers</h3><p>This setup separates the “Boys from the Men” (or the “Juniors from the Seniors”). Implementing Silent Refresh shows you understand security, HTTP lifecycles, and user experience.</p><p>Now go build something secure! 🔒</p><p><em>Thanks for reading! If you found this helpful, drop a clap 👏 and follow for more Full Stack guides.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79b621d903b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eureka + Retrofit: Dynamic Inter-Service Communication Made Easy in Spring Boot]]></title>
            <link>https://medium.com/@shivam.72329/eureka-retrofit-dynamic-inter-service-communication-made-easy-in-spring-boot-4a98d8412c9c?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a98d8412c9c</guid>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 11:41:34 GMT</pubDate>
            <atom:updated>2025-10-31T11:53:40.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjsUg7gc1DMB3NMQbnY3Bw.jpeg" /><figcaption>Eureka + Retrofit</figcaption></figure><p>In a microservices ecosystem, service discovery plays a key role. Instead of hardcoding IPs or URLs, services can automatically register and discover each other through a registry. Netflix <strong>Eureka Server</strong> makes this simple to implement using <strong>Spring Cloud</strong>.</p><p>In this article, we’ll set up:</p><ul><li>A <strong>Eureka Server</strong></li><li>Two <strong>Eureka Clients</strong>: BookingService and LocationService</li></ul><p>Each service will be independent, lightweight, and discoverable.</p><h3>1. Create a Eureka Server</h3><h3>Step 1.1 — Add Dependencies</h3><p><strong>build.gradle</strong></p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.3.5&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br>group = &#39;com.example&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>repositories {<br>    mavenCentral()<br>}<br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:2023.0.3&quot;<br>    }<br>}<br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-server&#39;<br>}</pre><h3>Step 1.2 — Enable Eureka Server</h3><p><strong>EurekaServerApplication.java</strong></p><pre>package com.example.eurekaserver;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;<br>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaServerApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(EurekaServerApplication.class, args);<br>        System.out.println(&quot;Eureka Server is running...&quot;);<br>    }<br>}</pre><h3>Step 1.3 — Configure application.yml</h3><pre>server:<br>  port: 8761<br>spring:<br>  application:<br>    name: eureka-server<br>eureka:<br>  client:<br>    register-with-eureka: false<br>    fetch-registry: false</pre><p>Run the app and open <a href="http://localhost:8761/">http://localhost:8761</a>.<br> You’ll see the Eureka dashboard.</p><h3>2. Create a Eureka Client (BookingService Example)</h3><h3>Step 2.1 — Add Dependencies</h3><p><strong>build.gradle</strong></p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.3.5&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br>group = &#39;com.example&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>repositories {<br>    mavenCentral()<br>}<br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:2023.0.3&quot;<br>    }<br>}<br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;<br>}</pre><h3>Step 2.2 — Application Class</h3><p><strong>BookingServiceApplication.java</strong></p><pre>package com.example.bookingservice;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.client.discovery.EnableDiscoveryClient;<br>@SpringBootApplication<br>@EnableDiscoveryClient<br>public class BookingServiceApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(BookingServiceApplication.class, args);<br>        System.out.println(&quot;Booking Service is up and registered!&quot;);<br>    }<br>}</pre><h3>Step 2.3 — Configuration File</h3><p><strong>application.yml</strong></p><pre>server:<br>  port: 8085<br>spring:<br>  application:<br>    name: booking-service<br>eureka:<br>  client:<br>    register-with-eureka: true<br>    fetch-registry: true<br>    service-url:<br>      defaultZone: http://localhost:8761/eureka/<br>  instance:<br>    prefer-ip-address: true<br>    instance-id: ${spring.application.name}:${server.port}<br>    lease-renewal-interval-in-seconds: 10<br>    lease-expiration-duration-in-seconds: 30</pre><h3>3. Create Another Eureka Client (LocationService)</h3><p>You can replicate the same structure as BookingService.</p><p><strong>application.yml</strong></p><pre>server:<br>  port: 8081<br>spring:<br>  application:<br>    name: location-service<br>eureka:<br>  client:<br>    register-with-eureka: true<br>    fetch-registry: true<br>    service-url:<br>      defaultZone: http://localhost:8761/eureka/<br>  instance:<br>    prefer-ip-address: true<br>    instance-id: ${spring.application.name}:${server.port}</pre><p>Run the service and open Eureka Dashboard again.<br> You’ll see:</p><pre>BOOKING-SERVICE — UP (1)<br>LOCATION-SERVICE — UP (1)</pre><h3>4. Verifying Service Discovery</h3><p>Once both clients are registered, you can check Eureka’s dashboard at <a href="http://localhost:8761/">http://localhost:8761</a>.<br> Each service will show its IP, port, and registration status as “UP”.</p><h3>5. Summary</h3><p>Component Port Purpose Eureka Server 8761 Service Registry Booking Service 8085 Eureka Client Location Service 8081 Eureka Client</p><p>This setup ensures that each microservice can dynamically register itself and discover others without manual configuration. You can now extend this base to include load balancing, centralized configuration, and inter-service communication.</p><p>Would you like me to add <strong>a short Retrofit integration example</strong> (e.g., Booking-Service calling Location-Service via Eureka service name) to make it look even more complete for Medium publication?</p><p>Got it — here’s the <strong>continuation</strong> of your previous article, starting <strong>right after</strong> where you had ended (with the question “now time to make it professional by removing emojis”) and adding the <strong>Retrofit integration part</strong>, keeping everything minimal, professional, and ready-to-run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIQJ5KKTa7AmvQ9bHb-Krw.png" /></figure><p>Now lets implement Retrofit for easy interservice communication</p><h3>6. Adding Retrofit for Service-to-Service Communication</h3><p>Once your microservices are registered with <strong>Eureka</strong>, they can discover each other dynamically. However, you still need an HTTP client to make REST calls between services.<br> For that, we use <strong>Retrofit</strong>, a simple and type-safe HTTP client.</p><h3>Step 1: Add Retrofit Dependency</h3><p>Add the following dependency to your <strong>client service</strong> (for example, booking-service) in build.gradle:</p><pre>dependencies {<br>    implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>    implementation &#39;com.squareup.retrofit2:converter-gson:2.9.0&#39;<br>}</pre><h3>Step 2: Create a Retrofit Configuration</h3><p>You can use Eureka’s service name to communicate instead of a hardcoded URL.</p><pre>package com.example.bookingservice.config;<br>import org.springframework.cloud.client.discovery.DiscoveryClient;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import retrofit2.Retrofit;<br>import retrofit2.converter.gson.GsonConverterFactory;<br>@Configuration<br>public class RetrofitConfig {<br>    private final DiscoveryClient discoveryClient;<br>    public RetrofitConfig(DiscoveryClient discoveryClient) {<br>        this.discoveryClient = discoveryClient;<br>    }<br>    @Bean<br>    public Retrofit retrofit() {<br>        // Resolve Entity Service&#39;s base URL from Eureka<br>        String baseUrl = discoveryClient.getInstances(&quot;entity-service&quot;)<br>                .stream()<br>                .findFirst()<br>                .map(si -&gt; si.getUri().toString())<br>                .orElseThrow(() -&gt; new RuntimeException(&quot;Entity service not found in Eureka&quot;));<br>        return new Retrofit.Builder()<br>                .baseUrl(baseUrl + &quot;/&quot;)<br>                .addConverterFactory(GsonConverterFactory.create())<br>                .build();<br>    }<br>}</pre><h3>Step 3: Define a Retrofit Client Interface</h3><p>Example interface for calling an endpoint from entity-service:</p><pre>package com.example.bookingservice.client;<br>import com.example.bookingservice.model.ExactLocation;<br>import retrofit2.Call;<br>import retrofit2.http.GET;<br>import retrofit2.http.Path;<br>public interface EntityServiceClient {<br>    @GET(&quot;/locations/{id}&quot;)<br>    Call&lt;ExactLocation&gt; getLocationById(@Path(&quot;id&quot;) Long id);<br>}</pre><h3>Step 4: Use the Client in a Service Class</h3><pre>package com.example.bookingservice.service;<br>import com.example.bookingservice.client.EntityServiceClient;<br>import com.example.bookingservice.model.ExactLocation;<br>import org.springframework.stereotype.Service;<br>import retrofit2.Retrofit;<br>@Service<br>public class BookingService {<br>    private final EntityServiceClient entityServiceClient;<br>    public BookingService(Retrofit retrofit) {<br>        this.entityServiceClient = retrofit.create(EntityServiceClient.class);<br>    }<br>    public ExactLocation fetchLocation(Long id) {<br>        try {<br>            return entityServiceClient.getLocationById(id).execute().body();<br>        } catch (Exception e) {<br>            throw new RuntimeException(&quot;Failed to fetch location from Entity Service&quot;, e);<br>        }<br>    }<br>}</pre><h3>Step 5: Enable Service Discovery</h3><p>Make sure your <strong>booking-service</strong> also has this annotation:</p><pre>@EnableDiscoveryClient<br>@SpringBootApplication<br>public class BookingServiceApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(BookingServiceApplication.class, args);<br>    }<br>}</pre><h3>Step 6: Eureka Configuration Reminder</h3><p>Ensure your application.properties (or application.yml) contains:</p><pre>spring.application.name=booking-service<br>server.port=8085<br>---<br><br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true<br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.prefer-ip-address=true<br><br></pre><h3>Step 7: Verify the Flow</h3><ol><li>Start <strong>Eureka Server</strong></li><li>Start <strong>Entity Service</strong> (on port 8090)</li><li>Start <strong>Booking Service</strong> (on port 8085)</li></ol><p>Booking Service will automatically discover the Entity Service via <strong>Eureka</strong>, fetch its base URL dynamically, and communicate using <strong>Retrofit</strong> without any hard-coded IP.</p><h3>Conclusion</h3><p>You now have a clean, production-ready setup where:</p><ul><li>Eureka handles service discovery.</li><li>Retrofit handles HTTP communication between microservices.</li><li>Each service stays independent yet connected dynamically.</li></ul><p>This setup ensures <strong>zero hard coding</strong>, <strong>easy scaling</strong>, and <strong>true microservice communication</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a98d8412c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a User Registration System with Spring Security: Chapter 1]]></title>
            <link>https://medium.com/@shivam.72329/building-a-user-registration-system-with-spring-security-chapter-1-b9224be475fe?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9224be475fe</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 13:24:37 GMT</pubDate>
            <atom:updated>2025-10-09T13:39:02.320Z</atom:updated>
            <content:encoded><![CDATA[<pre>Chapter Topic Status<br>1 The Registration Process With Spring Security (Current)<br>2 Activate a New Account by Email Upcoming <br>3 Registration - Password Encoding Upcoming <br>4 The Registration API becomes RESTful Upcoming <br>5 Reset Your Password Upcoming <br>6 Password Strength and Rules Upcoming <br>7 Resend the Verification Email Upcoming <br>8 Updating Your Password Upcoming <br>9 Notify User of Login From New Device or Location Upcoming</pre><p>In this chapter, we’ll build a complete <strong>user registration flow</strong> using Spring Boot and Spring Security. You’ll learn the file structure, where to put each class, how to create custom validators, and how to connect everything together.</p><h3>Project Structure</h3><pre>src/main/java/com/example/registration<br>    ├── RegistrationApplication.java          // Main Spring Boot application<br>    ├── config/<br>    │     └── SecurityConfig.java             // Spring Security config<br>    ├── controller/<br>    │     └── RegistrationController.java     // Handles registration requests<br>    ├── dto/<br>    │     └── UserDto.java                    // Data Transfer Object (form input)<br>    ├── model/<br>    │     └── User.java                       // Entity mapped to DB table<br>    ├── repository/<br>    │     └── UserRepository.java             // JPA repository for users<br>    ├── service/<br>    │     ├── IUserService.java               // Interface for service<br>    │     └── UserService.java                // Implementation of user logic<br>    ├── annotation/<br>    │     ├── ValidEmail.java                 // Custom annotation<br>    │     └── PasswordMatches.java            // Custom annotation<br>    └── validator/<br>          ├── EmailValidator.java             // Logic for email validation<br>          └── PasswordMatchesValidator.java   // Logic for password matchingsrc/main/resources/templates/<br>src/main/resources/templates/<br>    ├── registration.html                     // The user-facing registration form<br>    └── successRegister.html                  // The page shown after successful registration</pre><h3>Step 1: User DTO</h3><p>The UserDto class holds form input and applies both built-in and custom validations.</p><pre>@Data<br>@PasswordMatches<br>public class UserDto {<br>    @NotEmpty<br>    private String firstName;<br>    @NotEmpty<br>    private String lastName;<br>    @ValidEmail<br>    @NotEmpty<br>    private String email;<br>    @NotEmpty<br>    private String password;<br>    @NotEmpty<br>    private String matchingPassword;<br>}</pre><h3>Explanation</h3><ul><li>@PasswordMatches → custom annotation ensuring password and matchingPassword are same.</li><li>@ValidEmail → custom annotation validating email format.</li><li>These are handled by validators (next step).</li></ul><h3>Step 2: Custom Annotations</h3><h3>PasswordMatches.java</h3><pre>@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})<br>@Retention(RetentionPolicy.RUNTIME)<br>@Constraint(validatedBy = PasswordMatchesValidator.class)<br>@Documented<br>public @interface PasswordMatches {<br>    String message() default &quot;Passwords don&#39;t match&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><h3>ValidEmail.java</h3><pre>@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})<br>@Retention(RetentionPolicy.RUNTIME)<br>@Constraint(validatedBy = EmailValidator.class)<br>@Documented<br>public @interface ValidEmail {<br>    String message() default &quot;Invalid email&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><h3>Step 3: Custom Validators</h3><h3>PasswordMatchesValidator.java</h3><pre>public class PasswordMatchesValidator implements ConstraintValidator&lt;PasswordMatches, Object&gt; {<br>@Override<br>    public void initialize(PasswordMatches constraintAnnotation) {}<br>    @Override<br>    public boolean isValid(Object obj, ConstraintValidatorContext context) {<br>        UserDto user = (UserDto) obj;<br>        return user.getPassword().equals(user.getMatchingPassword());<br>    }<br>}</pre><h3>EmailValidator.java</h3><pre>public class EmailValidator implements ConstraintValidator&lt;ValidEmail, String&gt; {<br>private static final String EMAIL_PATTERN = &quot;^[A-Za-z0-9+_.-]+@(.+)$&quot;;<br>    @Override<br>    public boolean isValid(String email, ConstraintValidatorContext context) {<br>        return email != null &amp;&amp; email.matches(EMAIL_PATTERN);<br>    }<br>}</pre><blockquote><em>✅ Note: These validator classes do </em><strong><em>not</em></strong><em> need to be registered as beans in configuration. Spring automatically uses them when your DTO is annotated with </em><em>@Valid.</em></blockquote><h3>Step 4: Entity Class</h3><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class User {<br>@Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String firstName;<br>    private String lastName;<br>    @Column(unique = true)<br>    private String email;<br>    private String password;<br>}</pre><h3>Step 5: Repository</h3><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    User findByEmail(String email);<br>}</pre><h3>Step 6: Service Layer</h3><h3>IUserService.java</h3><pre>public interface IUserService {<br>    User registerNewUserAccount(UserDto userDto);<br>    boolean emailExists(String email);<br>}</pre><h3>UserService.java</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class UserService implements IUserService {<br>private final UserRepository userRepository;<br>    private final PasswordEncoder passwordEncoder;<br>    @Override<br>    public User registerNewUserAccount(UserDto userDto) {<br>        if (emailExists(userDto.getEmail())) {<br>            throw new RuntimeException(&quot;There is already an account with that email&quot;);<br>        }<br>        User user = new User();<br>        user.setFirstName(userDto.getFirstName());<br>        user.setLastName(userDto.getLastName());<br>        user.setEmail(userDto.getEmail());<br>        user.setPassword(passwordEncoder.encode(userDto.getPassword()));<br>        return userRepository.save(user);<br>    }<br>    @Override<br>    public boolean emailExists(String email) {<br>        return userRepository.findByEmail(email) != null;<br>    }<br>}</pre><h3>Step 7: Registration Controller</h3><pre>@Controller<br>@RequiredArgsConstructor<br>public class RegistrationController {<br>private final IUserService userService;<br>    @GetMapping(&quot;/user/registration&quot;)<br>    public String showRegistrationForm(Model model) {<br>        model.addAttribute(&quot;user&quot;, new UserDto());<br>        return &quot;registration&quot;;<br>    }<br>    @PostMapping(&quot;/user/registration&quot;)<br>    public String registerUserAccount(@ModelAttribute(&quot;user&quot;) @Valid UserDto userDto,<br>                                      BindingResult result, Model model) {<br>        if (result.hasErrors()) {<br>            return &quot;registration&quot;;<br>        }<br>        try {<br>            userService.registerNewUserAccount(userDto);<br>        } catch (Exception e) {<br>            model.addAttribute(&quot;registrationError&quot;, e.getMessage());<br>            return &quot;registration&quot;;<br>        }<br>        return &quot;redirect:/registrationSuccess&quot;;<br>    }<br>    @GetMapping(&quot;/registrationSuccess&quot;)<br>    public String registrationSuccess() {<br>        return &quot;successRegister&quot;;<br>    }<br>}</pre><h3>Explanation</h3><ul><li>@Valid triggers the validators attached to UserDto.</li><li>If there are errors, it re-renders the same registration page with messages.</li><li>On success, it redirects to the success page.</li></ul><h3>Step 8: Security Configuration</h3><pre>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>public class SecurityConfig {<br>private final PasswordEncoder passwordEncoder;<br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        http<br>            .csrf().disable()<br>            .authorizeHttpRequests()<br>                .requestMatchers(&quot;/user/registration&quot;, &quot;/registrationSuccess&quot;, &quot;/css/**&quot;, &quot;/js/**&quot;).permitAll()<br>                .anyRequest().authenticated()<br>            .and()<br>            .formLogin()<br>                .loginPage(&quot;/login&quot;)<br>                .permitAll()<br>            .and()<br>            .logout()<br>                .permitAll();<br>        return http.build();<br>    }<br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><blockquote><em>🧠 Note: We’re allowing unauthenticated users to access </em><em>/user/registration and </em><em>/registrationSuccess, while other routes require login.</em></blockquote><h3>Step 9: Thymeleaf Templates</h3><h3>registration.html</h3><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot; xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Registration&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;User Registration&lt;/h2&gt;<br>    &lt;form th:action=&quot;@{/user/registration}&quot; th:object=&quot;${user}&quot; method=&quot;post&quot;&gt;<br>        &lt;p&gt;<br>            &lt;label for=&quot;firstName&quot;&gt;First Name&lt;/label&gt;<br>            &lt;input id=&quot;firstName&quot; type=&quot;text&quot; th:field=&quot;*{firstName}&quot; required /&gt;<br>            &lt;span th:if=&quot;${#fields.hasErrors(&#39;firstName&#39;)}&quot; th:errors=&quot;*{firstName}&quot;&gt;&lt;/span&gt;<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>            &lt;label for=&quot;lastName&quot;&gt;Last Name&lt;/label&gt;<br>            &lt;input id=&quot;lastName&quot; type=&quot;text&quot; th:field=&quot;*{lastName}&quot; required /&gt;<br>            &lt;span th:if=&quot;${#fields.hasErrors(&#39;lastName&#39;)}&quot; th:errors=&quot;*{lastName}&quot;&gt;&lt;/span&gt;<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>            &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;<br>            &lt;input id=&quot;email&quot; type=&quot;email&quot; th:field=&quot;*{email}&quot; required /&gt;<br>            &lt;span th:if=&quot;${#fields.hasErrors(&#39;email&#39;)}&quot; th:errors=&quot;*{email}&quot;&gt;&lt;/span&gt;<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>            &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;<br>            &lt;input id=&quot;password&quot; type=&quot;password&quot; th:field=&quot;*{password}&quot; required /&gt;<br>            &lt;span th:if=&quot;${#fields.hasErrors(&#39;password&#39;)}&quot; th:errors=&quot;*{password}&quot;&gt;&lt;/span&gt;<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>            &lt;label for=&quot;matchingPassword&quot;&gt;Confirm Password&lt;/label&gt;<br>            &lt;input id=&quot;matchingPassword&quot; type=&quot;password&quot; th:field=&quot;*{matchingPassword}&quot; required /&gt;<br>            &lt;span th:if=&quot;${#fields.hasErrors(&#39;matchingPassword&#39;)}&quot; th:errors=&quot;*{matchingPassword}&quot;&gt;&lt;/span&gt;<br>        &lt;/p&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Register&lt;/button&gt;<br>    &lt;/form&gt;<br><br>    &lt;p th:if=&quot;${registrationError}&quot; th:text=&quot;${registrationError}&quot; style=&quot;color:red;&quot;&gt;&lt;/p&gt;<br>    &lt;div th:if=&quot;${#fields.hasErrors(&#39;${user.*}&#39;)}&quot;&gt;<br>        &lt;p style=&quot;color:red;&quot;&gt;Please correct the errors above&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>successRegister.html</h3><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Success&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Registration Successful!&lt;/h2&gt;<br>    &lt;p&gt;Your account has been created successfully.&lt;/p&gt;<br>    &lt;a href=&quot;/login&quot;&gt;Go to Login&lt;/a&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Step 10: Run and Test</h3><p>You are now ready to run the application.</p><ol><li>Make sure you have your database configured in application.properties (e.g., for MySQL, H2, etc.).</li><li>Run the application from your IDE or using the command line:</li><li>Bash</li></ol><pre>mvn spring-boot:run</pre><ol><li>Navigate to http://localhost:8080/user/registration in your web browser.</li><li>Test the validations: try submitting an empty form, using an invalid email format, or using non-matching passwords. Then, try registering a user that already exists.</li><li>Finally, register a new user successfully. You should be redirected to the success page, and the new user — with an encoded password — will be saved in your database.</li></ol><h3>✅ Summary</h3><p>Congratulations! You have successfully built a complete and secure user registration module. We have:</p><ul><li>Separated concerns using a clean project structure.</li><li>Used a DTO to safely transfer data from the web form.</li><li>Created powerful, reusable custom validators.</li><li>Implemented a service layer to handle business logic and orchestrate database operations.</li><li>Properly hashed user passwords before saving them.</li><li>Configured Spring Security to protect our application while allowing access to the registration page.</li></ul><p>In <strong>Chapter 2</strong>, we’ll extend this project to include <strong>email verification and login flow</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9224be475fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JPA Relationships: One-to-One, One-to-Many, Many-to-One & Many-to-Many]]></title>
            <link>https://medium.com/@shivam.72329/mastering-jpa-relationships-one-to-one-one-to-many-many-to-one-many-to-many-6668b510e0f6?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/6668b510e0f6</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[relationshiops]]></category>
            <category><![CDATA[association]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 11:48:38 GMT</pubDate>
            <atom:updated>2026-05-17T03:22:46.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Best article to master and visualise JPA Relationships: One-to-One, One-to-Many, Many-to-One &amp; Many-to-Many</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZnskGcHT9rJS5VFbMupGw.jpeg" /></figure><h3>🧠 Introduction</h3><p>Understanding relationships in <strong>JPA (Java Persistence API)</strong> or <strong>Hibernate</strong> is essential for designing <strong>clean, efficient, and maintainable database schemas</strong>.</p><p>In this article, we’ll cover the <strong>four main JPA relationships</strong> with <strong>code examples, database tables, and guidance on where to use </strong><strong>@JoinColumn</strong>, making it easy for beginners to follow.</p><h3>1️⃣ One-to-One Relationship</h3><h3>Concept</h3><ul><li>One entity is linked to <strong>exactly one</strong> other entity.</li><li>Example: One Employee has one EmployeeDetail.</li></ul><h3>Code Example</h3><pre>@Entity<br>public class Employee {<br>    @Id<br>    private Long id;<br>    private String name;<br>@OneToOne<br>    @JoinColumn(name = &quot;detail_id&quot;) // FK lives here<br>    private EmployeeDetail detail;<br>}<br>@Entity<br>public class EmployeeDetail {<br>    @Id<br>    private Long id;<br>    private String address;<br>    private String phoneNumber;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*sNAGYDC-hqRvHExpIibj2g.png" /></figure><p>✅ @JoinColumn is used <strong>on the entity that owns the foreign key</strong> (Employee in this case).</p><h3>2️⃣ One-to-Many Relationship</h3><h3>Concept</h3><ul><li>One entity (parent) can have <strong>multiple child entities</strong>.</li><li>Example: One Department has many Employees.</li></ul><h3>Code Example</h3><pre>@Entity<br>public class Department {<br>    @Id<br>    private Long id;<br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;department&quot;) // child owns FK<br>    private List&lt;Employee&gt; employees;<br>}<br><br><br>@Entity<br>public class Employee {<br>    @Id<br>    private Long id;<br>    private String name;<br>    @ManyToOne<br>    @JoinColumn(name = &quot;department_id&quot;) // FK in child table<br>    private Department department;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*PyOuqfOSbnb-ft_FgupDMQ.png" /></figure><p>✅ @JoinColumn is <strong>always on the child table</strong> (Employee).</p><h3>3️⃣ Many-to-One Relationship</h3><h3>Concept</h3><ul><li>Reverse of One-to-Many.</li><li>Many Employees can belong to <strong>one Department</strong>.</li></ul><h3>Code Example</h3><pre>@Entity<br>public class Employee {<br>    @Id<br>    private Long id;<br>    private String name;<br><br>    @ManyToOne<br>    @JoinColumn(name = &quot;department_id&quot;) // FK in child table<br>    private Department department;<br>}<br><br><br>@Entity<br>public class Department {<br>    @Id<br>    private Long id;<br>    private String name;<br>}</pre><h3>Database Tables</h3><p><strong>→Employee</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*901jjdKAFSEQshZ4P6iLOQ.png" /></figure><p>✅ @JoinColumn is <strong>used on the child table</strong> (Employee).</p><h3>4️⃣ Bidirectional One-to-Many &amp; Many-to-One</h3><h3>Concept</h3><ul><li>Enables navigation <strong>both ways</strong>:</li><li>Department → Employees</li><li>Employee → Department</li></ul><h3>Code Example</h3><pre>@Entity<br>public class Department {<br>    @Id<br>    private Long id;<br>    private String name;<br><br>    @OneToMany(mappedBy = &quot;department&quot;)<br>    private List&lt;Employee&gt; employees;<br>}<br><br><br><br>@Entity<br>public class Employee {<br>    @Id<br>    private Long id;<br>    private String name;<br>    @ManyToOne<br>    @JoinColumn(name = &quot;department_id&quot;) // FK in child<br>    private Department department;<br>}</pre><h3>Usage Example</h3><pre>Employee e = entityManager.find(Employee.class, 101L);<br>System.out.println(e.getDepartment().getName()); // HR<br><br>Department d = entityManager.find(Department.class, 1L);<br>d.getEmployees().forEach(emp -&gt; System.out.println(emp.getName()));<br>// Output: Alice, Bob</pre><h3>5️⃣ Many-to-Many Relationship</h3><h3>Concept</h3><ul><li>Both entities can have <strong>multiple associations</strong>.</li><li>Example: Employees can work in multiple Departments.</li></ul><h3>Code Example</h3><pre>@Entity<br>public class Employee {<br>    @Id<br>    private Long id;<br>    private String name;<br><br>    @ManyToMany<br>    @JoinTable(<br>        name = &quot;employee_department&quot;,<br>        joinColumns = @JoinColumn(name = &quot;employee_id&quot;), // FK in join table<br>        inverseJoinColumns = @JoinColumn(name = &quot;department_id&quot;)<br>    )<br>    private List&lt;Department&gt; departments;<br>}<br><br><br><br>@Entity<br>public class Department {<br>    @Id<br>    private Long id;<br>    private String name;<br>}</pre><h3>Database Tables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*viVDkRLVP1ZQSDkLlC5IZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*4YoBz5G_nOCYXmZG-uyDkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*oGJf1AA9jFQM_GxZcWlfTw.png" /></figure><p>✅ @JoinTable is used instead of @JoinColumn, and it can be declared on <strong>either side</strong> of the relationship.</p><h3>✅ Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*Jnj1G0Tefpb95AGuDLysHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*LZCaFGHstz50QdTIOCRJVQ.png" /></figure><h3>💬 Conclusion</h3><p>Mastering JPA relationships is key to <strong>efficient database design</strong>.</p><ul><li>Understand <strong>where the foreign key lives</strong></li><li>Know <strong>where to use </strong><strong>@JoinColumn</strong></li></ul><p>Choose the <strong>correct relationship type</strong> for your use case</p><p>Once mastered, JPA makes <strong>object-relational mapping intuitive and clean</strong>, enabling maintainable and scalable applications.</p><p>✍️ <em>Written by Shivam Chaturvedi</em><br> 📍 Ayodhya, India</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6668b510e0f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Setting Up Flyway Database Migrations in Spring Boot (Java + MySQL)]]></title>
            <link>https://medium.com/@shivam.72329/setting-up-flyway-database-migrations-in-spring-boot-java-mysql-37746456ada2?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/37746456ada2</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[intellij-idea]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 09:46:21 GMT</pubDate>
            <atom:updated>2025-10-04T09:46:21.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekoo2ApWNvBiAppUl3xmXQ.png" /></figure><p>Database schema management is one of the most overlooked yet crucial aspects of building production-grade applications. If you’ve ever broken production because of a missing SQL script — you know the pain. Thankfully, <strong>Flyway</strong> provides a structured way to manage versioned database migrations automatically.</p><p>In this article, we’ll go through how to set up <strong>Flyway</strong> in a Spring Boot project using <strong>Gradle</strong> and <strong>MySQL</strong>, and we’ll also explore how to add and run migrations using <strong>IntelliJ IDEA’s persistence tool</strong>.</p><h3>What is Flyway?</h3><p><strong>Flyway</strong> is a database migration tool that helps version, track, and apply schema changes. It integrates smoothly with Spring Boot, meaning it can automatically detect and run migration scripts when your application starts.</p><p>Flyway migration files are typically stored in:</p><pre>src/main/resources/db/migration/</pre><p>Each migration file must follow a naming convention like:</p><pre>V1__init_schema.sql<br>V2__add_user_table.sql</pre><h3>🧩 Step 1: Add Flyway Dependencies</h3><p>In your build.gradle file, add the following dependencies:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;maven-publish&#39;<br>}<br><br>group = &#39;org.example&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>description = &#39;FlywayDemo&#39;<br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(17)<br>    }<br>}<br>repositories {<br>    mavenCentral()<br>}<br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa:3.2.5&#39;<br>    // Lombok<br>    compileOnly &#39;org.projectlombok:lombok:1.18.32&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok:1.18.32&#39;<br>    // MySQL Driver<br>    runtimeOnly &#39;com.mysql:mysql-connector-j:8.4.0&#39;<br>    // Flyway Migration<br>    implementation &#39;org.flywaydb:flyway-core:10.15.0&#39;<br>    implementation &#39;org.flywaydb:flyway-mysql:10.15.0&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test:3.2.5&#39;<br>}<br>publishing {<br>    publications {<br>        mavenJava(MavenPublication) {<br>            from components.java<br>        }<br>    }<br>    repositories {<br>        mavenLocal()<br>    }<br>}<br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><blockquote><em>💡 Note: Adding both </em><em>flyway-core and </em><em>flyway-mysql ensures that Flyway understands MySQL-specific dialects.</em></blockquote><h3>️ Step 2: Configure Flyway in application.properties</h3><p>Inside your src/main/resources/application.properties, define your database connection and Flyway settings:</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/uber_project<br>spring.datasource.username=root<br>spring.datasource.password=your_password<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br># Flyway Configuration<br>spring.flyway.enabled=true<br>spring.flyway.locations=classpath:db/migration<br>spring.flyway.baseline-on-migrate=true</pre><blockquote><em>✅ The property </em><em>spring.flyway.baseline-on-migrate=true allows Flyway to initialize version control on an existing database without wiping data.</em></blockquote><h3>🗂 Step 3: Create Migration Scripts</h3><p>Migration scripts must be placed in src/main/resources/db/migration.</p><p>Example:</p><pre>src/<br> └── main/<br>     └── resources/<br>         └── db/<br>             └── migration/<br>                 ├── V1__create_user_table.sql<br>                 ├── V2__add_column_email_to_user.sql</pre><p><strong>Example: V1__create_user_table.sql</strong></p><pre>CREATE TABLE users (<br>    id BIGINT AUTO_INCREMENT PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><h3>🧠 Step 4: Running Migrations Automatically</h3><p>When you start your Spring Boot application using:</p><pre>./gradlew bootRun</pre><p>Flyway will automatically detect the migration files and apply any new migrations that haven’t yet been executed.</p><p>You’ll see something like this in the logs:</p><pre>Flyway Community Edition 10.x by Redgate<br>Database: jdbc:mysql://localhost:3306/uber_project (MySQL 8.0)<br>Successfully applied 2 migrations to schema `uber_project` (execution time 00:00.123s)</pre><h3>💻 Step 5: Adding and Running Migrations via IntelliJ IDEA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vST4eX9ptGmKsQ3zvGpvrQ.png" /><figcaption>Check at left side bar, Persistence section allow you handle your migration easily</figcaption></figure><p>IntelliJ provides a <strong>Persistence Tool Window</strong> to manage database migrations visually.</p><h3>🧭 Steps:</h3><ol><li>Open <strong>View → Tool Windows → Database</strong>.</li><li>Click the + icon → choose <strong>Data Source → MySQL</strong>.</li><li>Enter your MySQL connection details and test the connection.</li><li>Once connected, open <strong>Flyway Migrations → Manage Migrations</strong>.</li><li>You can now run Migrate, Repair, or Clean commands right from IntelliJ.</li><li>To add a new migration, right-click on the db/migration folder → <strong>New → SQL File</strong>.</li></ol><ul><li>Name it using Flyway’s convention, e.g., V3__add_address_table.sql.</li></ul><blockquote><em>⚡ IntelliJ automatically detects Flyway configurations in </em><em>application.properties.</em></blockquote><h3>🧾 Step 6: Verifying Migration History</h3><p>Flyway keeps track of all applied migrations in a special table:</p><pre>SELECT * FROM flyway_schema_history;</pre><p>This table logs version, description, execution time, and checksum — ensuring integrity and preventing re-application.</p><h3>Step 7: Publishing Locally (Optional)</h3><p>If you’re building a library that includes Flyway migrations (for microservice modularity), you can publish it locally using:</p><pre>./gradlew publishToMavenLocal</pre><p>This makes it available under ~/.m2/repository for other local projects.</p><h3>✅ Summary</h3><p>Step Action Description 1 Add dependencies Add Flyway and MySQL support 2 Configure Flyway Set properties in application.properties 3 Create scripts Write SQL migrations under db/migration 4 Run app Migrations run automatically 5 Use IntelliJ Add/manage migrations visually 6 Check history Inspect flyway_schema_history table 7 Optional Publish library locally</p><h3>🏁 Final Thoughts</h3><p>Flyway simplifies database evolution, eliminates migration chaos, and integrates beautifully with Spring Boot. Whether you’re a solo dev or part of a large microservice team, it ensures your database schema evolves reliably alongside your codebase.</p><blockquote><em>✨ Bonus Tip: Combine Flyway with CI/CD (like GitHub Actions or Jenkins) to automate migration runs in staging and production.</em></blockquote><p>💻 <strong>Tech Stack:</strong> Spring Boot | MySQL | Flyway | IntelliJ IDEA<br> 🕊️ <em>“Evolve your database as easily as your code.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37746456ada2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting a Java Project into a Reusable Library: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@shivam.72329/converting-a-java-project-into-a-reusable-library-a-step-by-step-guide-73bc87b14a59?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bc87b14a59</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 17:53:02 GMT</pubDate>
            <atom:updated>2025-10-03T17:55:58.414Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Converting a Java Project to a Library: Avoid the </strong><strong>@EntityScan Pitfall</strong></p><p>Step1: <a href="https://medium.com/@shivam.72329/converting-a-spring-boot-application-into-a-reusable-library-step-by-step-1b51fd4753e5">For setup from basic follow this article first </a>↗ ️</p><p>When working on Java projects, there often comes a time when you want to <strong>reuse code across multiple projects</strong>. Instead of copying and pasting classes, the cleanest approach is to <strong>convert your project into a library</strong>. This not only promotes code reuse but also makes your project modular and maintainable.</p><p>In this guide, we’ll walk through the process of converting a typical Java project into a library using <strong>Maven</strong>, including a <strong>crucial </strong><strong>@EntityScan step</strong> for Spring-based projects.</p><h3>1. Structure Your Project Properly</h3><p>First, make sure your project follows a <strong>standard Maven structure</strong>:</p><pre>my-library/<br> ├── pom.xml<br> └── src/<br>     └── main/<br>         ├── java/<br>         │    └── com/example/mylibrary/<br>         │         └── MyClass.java<br>         └── resources/</pre><p>If your project uses <strong>Spring Boot</strong>, ensure your entities and configurations are inside proper packages.</p><h3>2. Update pom.xml for a Library</h3><p>Change your pom.xml packaging type from jar (or war) to jar if it isn’t already:</p><pre>&lt;project ...&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-library&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;packaging&gt;jar&lt;/packaging&gt;<br><br><br>&lt;dependencies&gt;<br>        &lt;!-- Add necessary dependencies --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/project&gt;</pre><blockquote><em>🔑 Note: Make sure </em><strong><em>dependencies you include are only those required for the library</em></strong><em>, not the entire application.</em></blockquote><h3>3. Add @EntityScan for JPA Entities</h3><p>If your library contains <strong>JPA entities</strong>, Spring Boot will not automatically scan them when you import the library into another project. To fix this, use @EntityScan in the main application class of the consuming project:</p><pre>@SpringBootApplication<br>@EntityScan(basePackages = &quot;com.example.mylibrary.entities&quot;)<br>public class MyApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApplication.class, args);<br>    }<br>}</pre><p>This ensures that Spring Boot <strong>detects all entities from your library</strong>.</p><blockquote><em>⚡ Pro Tip: Always keep entities in a separate package like </em><em>com.example.mylibrary.entities to avoid conflicts.</em></blockquote><h3>4. Build the Library</h3><p>Use Maven to build your library:</p><pre>mvn clean install</pre><p>This will create a <strong>JAR file</strong> in your local Maven repository (~/.m2/repository/com/example/my-library/1.0.0/my-library-1.0.0.jar).</p><h3>5. Import Your Library into Another Project</h3><p>Now, in your <strong>consuming project</strong>, add your library as a dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;my-library&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Or, if you are working locally and don’t want to push to a remote repo, ensure your local Maven repository has the JAR installed.</p><h3>6. Use Your Library Classes</h3><p>You can now directly import and use classes from your library:</p><pre>import com.example.mylibrary.MyClass;<br>public class Demo {<br>    public static void main(String[] args) {<br>        MyClass myClass = new MyClass();<br>        myClass.doSomething();<br>    }<br>}</pre><p>For Spring-based projects, also ensure your beans and configurations are properly scanned.</p><h3>7. Optional: Make Your Library Modular</h3><p>To further enhance <strong>reusability</strong>, you can:</p><ul><li>Separate entities, services, and utilities into distinct packages.</li><li>Include a README.md in your library explaining its usage.</li><li>Provide versioning to manage updates smoothly.</li></ul><h3>✅ Key Takeaways</h3><ul><li>Converting a project to a library avoids <strong>duplicate code</strong>.</li><li>Use @EntityScan in Spring projects to ensure JPA entities are detected.</li><li>Always follow a <strong>clean Maven structure</strong> and define dependencies carefully.</li><li>Test your library by importing it into a new project before publishing.</li></ul><p>By following these steps, your Java project becomes a <strong>reusable, maintainable library</strong> ready for multiple applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bc87b14a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Converting a Spring Boot Application into a Reusable Library (Step by Step)]]></title>
            <link>https://medium.com/@shivam.72329/converting-a-spring-boot-application-into-a-reusable-library-step-by-step-1b51fd4753e5?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b51fd4753e5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 17:10:04 GMT</pubDate>
            <atom:updated>2025-10-03T17:58:24.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGlw3mBgAHh6kk-YCR6FnA.png" /></figure><p>Often when building microservices or larger Spring-based systems, we realize that some code (like entities, repositories, or utilities) is reusable across multiple services. Instead of duplicating code, we can <strong>convert a Spring Boot application into a library JAR</strong> and reuse it.</p><p>In this guide, I’ll walk you through converting a fresh Spring Boot application into a library project that can be consumed by other Spring projects.</p><h3>🔹 1. Start with a New Spring Boot App</h3><p>Let’s assume you generated a new project with Spring Initializr:</p><pre>spring init --dependencies=web,data-jpa,lombok demo-app<br>cd demo-app</pre><p>This project, by default, is a runnable Spring Boot application.</p><p><strong>Default </strong><strong>build.gradle plugins look like this:</strong></p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.2.5&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.4&#39;<br>}</pre><p>This setup builds an executable Spring Boot JAR (fat JAR).</p><p>But for a <strong>library</strong>, we don’t want a fat JAR. We just want a simple JAR with reusable code.</p><h3>🔹 2. Change Gradle Configuration to a Library</h3><p>Update your build.gradle to remove the spring-boot and dependency-management plugins, and add maven-publish.</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;maven-publish&#39;<br>}<br><br>group = &#39;org.example&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>description = &#39;Demo Library Service&#39;<br><br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(17)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br>configurations {<br>    compileOnly {<br>        extendsFrom annotationProcessor<br>    }<br>}<br>dependencies {<br>    // Add explicit versions (since dependency-management plugin is gone)<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa:3.2.5&#39;<br>    compileOnly &#39;org.projectlombok:lombok:1.18.32&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok:1.18.32&#39;<br>    annotationProcessor &#39;org.springframework.boot:spring-boot-configuration-processor:3.2.5&#39;<br>    runtimeOnly &#39;com.mysql:mysql-connector-j:8.4.0&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test:3.2.5&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher:1.10.2&#39;<br>}<br><br>publishing {<br>    publications {<br>        mavenJava(MavenPublication) {<br>            from components.java<br>        }<br>    }<br>    repositories {<br>        // Publish into local Maven (~/.m2)<br>        mavenLocal()<br>    }<br>}<br><br>// JUnit 5 setup<br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><pre>Now the project will build a plain JAR instead of a fat Spring Boot JAR.</pre><h3>🔹 3. Fix the Tests</h3><p>Spring Initializr creates a default test like this:</p><pre>@SpringBootTest<br>class DemoAppTests {<br>    @Test<br>    void contextLoads() {<br>    }<br>}</pre><p>This tries to start a full Spring Boot context, which fails in a library (no data source, no config). Replace it with a simple JUnit test:</p><pre>import org.junit.jupiter.api.Test;<br>import static org.junit.jupiter.api.Assertions.assertTrue;<br>//@SpringBootTest (remove this annotation)<br>class DemoAppTests {<br>    @Test<br>    void simpleTest() {<br>        assertTrue(true);<br>    }<br>}</pre><p>This ensures your Gradle build succeeds.</p><h3>🔹 3.1 If You Want to Keep Integration Tests</h3><p>If your library contains entities and JPA repositories and you still want to test them:</p><ol><li>Add H2 as a test dependency:</li></ol><pre>testImplementation &#39;com.h2database:h2:2.2.224&#39;</pre><ol><li>Create a src/test/resources/application-test.properties file:</li></ol><pre>spring.datasource.url=jdbc:h2:mem:testdb<br>spring.datasource.driver-class-name=org.h2.Driver<br>spring.jpa.hibernate.ddl-auto=create-drop</pre><ol><li>Update your test class:</li></ol><pre>import org.junit.jupiter.api.Test;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.test.context.ActiveProfiles;<br><br>@SpringBootTest<br>@ActiveProfiles(&quot;test&quot;)<br>class DemoAppTests {<br>    @Test<br>    void contextLoads() {<br>        // Context should start with in-memory H2<br>    }<br>}</pre><p>This way, your tests will spin up a Spring Boot context with an in-memory DB, allowing you to validate JPA mappings.</p><h3>4. Build and Publish the Library</h3><p>Run:</p><pre>./gradlew clean build publishToMavenLocal</pre><p>This will:</p><ul><li>Build a JAR under build/libs.</li><li>Publish the JAR into your local Maven repo (~/.m2/repository).</li></ul><h3>🔹 5. Use the Library in Another Spring Boot Project</h3><p>In your other project’s build.gradle, add:</p><pre>dependencies {<br>    implementation &#39;org.example:demo-app:0.0.1-SNAPSHOT&#39;<br>}</pre><p>Gradle will pull the JAR from ~/.m2/repository.</p><p>Now you can reuse entities, repositories, configs, or any utilities packaged inside your library.</p><h3>🔹 6. (Optional) Make it a Spring Boot Starter</h3><p>If you want your library to auto-configure beans (like an official Spring Boot starter), you can:</p><ol><li>Add @Configuration classes.</li><li>Register them in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.</li><li>Package and publish as usual.</li></ol><p>When another project adds your dependency, Spring Boot will auto-detect your configurations.</p><h3>✅ Summary</h3><ol><li>Remove Spring Boot plugins → use plain java + maven-publish.</li><li>Add explicit versions for dependencies.</li><li>Replace @SpringBootTest with simple unit tests <strong>OR</strong> configure H2 for integration tests.</li><li>Publish with publishToMavenLocal.</li><li>Import the library into other Spring projects.</li></ol><p>With this approach, you’ve successfully <strong>converted a Spring Boot application into a reusable library</strong> 🚀.</p><p>💡 Pro tip: For team collaboration, instead of mavenLocal(), publish your library to a private Maven repository (like Nexus, Artifactory, or GitHub Packages).</p><p>📍 <a href="https://medium.com/@shivam.72329/converting-a-java-project-into-a-reusable-library-a-step-by-step-guide-73bc87b14a59"><em>if there comes error in fetching from the library in other project, follow this article</em></a><em> </em>↗️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b51fd4753e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering JWT Authentication in Spring Boot: Step-by-Step Guide-Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@shivam.72329/mastering-jwt-authentication-in-spring-boot-step-by-step-guide-beginner-friendly-guide-0d8ff22c56e6?source=rss-c5e4400b9cde------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d8ff22c56e6</guid>
            <dc:creator><![CDATA[Shivam ]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 08:02:23 GMT</pubDate>
            <atom:updated>2025-09-18T08:11:25.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering JWT Authentication in Spring Boot: Step-by-Step Guide-Beginner-Friendly Guide 🔐(With Code)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQZZ19LSDSDrnhOywCmuhg.png" /></figure><p>In today’s world of microservices and secure APIs, <strong>JWT (JSON Web Token)</strong> is one of the most popular methods for <strong>authentication and authorisation</strong>. If you’re building a Spring Boot application, JWT will help you secure your APIs in a stateless and scalable way.</p><p>In this article, we’ll build a <strong>JWT Service in Spring Boot</strong> from scratch, explain every part of the code, and also cover <strong>common mistakes</strong> to avoid.</p><h3>📌 What is JWT and Why Do We Need It?</h3><p>JWT is a <strong>compact and self-contained token</strong> used to securely transmit information between two parties (like client and server).<br> It has three parts:</p><ol><li><strong>Header</strong> — contains metadata like the signing algorithm.</li><li><strong>Payload</strong> — contains user data (email, role, etc.).</li><li><strong>Signature</strong> — ensures the token is not tampered with.</li></ol><p>Example JWT looks like this:</p><pre>xxxxx.yyyyy.zzzzz</pre><h3>🏗 Setting Up Dependencies</h3><p>Before writing any code, add the following dependencies to your <strong>Gradle</strong> file:</p><pre>implementation &#39;io.jsonwebtoken:jjwt-api:0.11.5&#39;<br>runtimeOnly &#39;io.jsonwebtoken:jjwt-impl:0.11.5&#39;<br>runtimeOnly &#39;io.jsonwebtoken:jjwt-jackson:0.11.5&#39; // for JSON parsing</pre><p>✅ <strong>Tip:</strong> Without these, you’ll get Cannot resolve symbol &#39;Keys&#39; or parsing errors.</p><h3>📌 Configuring Properties</h3><p>In your application.properties, define:</p><pre># JWT secret key (must be long enough for HS512)<br>jwt.secret=ThisIsASecretKeyThatIsAtLeast64BytesLongToBeSecure1234567890</pre><pre># Expiry time in milliseconds (e.g., 1 hour = 3600000)</pre><pre>jwt.expiry=3600000</pre><p>✅ <strong>Tip:</strong></p><ul><li>For <strong>HS256</strong>, secret must be <strong>&gt;= 32 bytes</strong>.</li><li>For <strong>HS512</strong>, secret must be <strong>&gt;= 64 bytes</strong>.<br> If your secret is shorter, you’ll get errors like:<br> The signing key&#39;s size is not secure enough for HS512.</li></ul><h3>⚡ Writing the JWT Service</h3><p>Here’s the full code with easy explanations.</p><h3>1. Service Declaration</h3><pre>@Service<br>public class JwtService implements CommandLineRunner {</pre><p>We mark it as a Spring @Service so it can be injected into other classes.<br> CommandLineRunner is just for <strong>testing at startup</strong> — we’ll generate and validate a sample token automatically.</p><h3>2. Loading Properties</h3><pre>@Value(&quot;${jwt.expiry}&quot;)<br>private int expiry;</pre><pre>@Value(&quot;${jwt.secret}&quot;)<br>private String SECRET;</pre><p>jwt.expiry → how long the token is valid.</p><p>jwt.secret → key to sign/verify tokens.</p><h3>3. Generating a Signing Key</h3><pre>private Key getSignKey(){<br>    return Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));<br>}</pre><p>We use Keys.hmacShaKeyFor() from <strong>jjwt</strong> to generate a cryptographic key.</p><p>✅ <strong>Tip:</strong> Don’t hardcode keys directly in code. Always store in <strong>application.properties</strong> or <strong>environment variables</strong>.</p><h3>4. Generating a Token</h3><pre>private String generateToken(Map&lt;String, Object&gt; payload, String email) {<br>    return Jwts.builder()<br>            .setClaims(payload)<br>            .setSubject(email) // the main identifier (usually email)<br>            .setIssuedAt(new Date(System.currentTimeMillis()))<br>            .setExpiration(new Date(System.currentTimeMillis() + expiry))<br>            .signWith(getSignKey(), SignatureAlgorithm.HS512)<br>            .compact();<br>}</pre><p><strong>payload</strong> = extra info (username, phone, etc.)</p><p><strong>subject (sub)</strong> = official identifier (we’ll use email)</p><p><strong>issuedAt &amp; expiration</strong> = when token was created and when it expires</p><p><strong>signWith</strong> = secures the token with our secret</p><p>✅ <strong>Tip:</strong> Always keep sub as <strong>email/username</strong> so you can validate identity easily later.</p><h3>5. Extracting Claims</h3><pre>private Claims extractAllPayloads(String token) {<br>    return Jwts.parserBuilder()<br>            .setSigningKey(getSignKey())<br>            .build()<br>            .parseClaimsJws(token)<br>            .getBody();<br>}</pre><p>This decodes the entire token and gives us <strong>all claims</strong> (subject, expiry, payload).</p><h3>6. Extracting a Specific Claim</h3><pre>public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver) {<br>    final Claims claims = extractAllPayloads(token);<br>    return claimsResolver.apply(claims);<br>}</pre><p>Example:</p><pre>extractClaim(token, Claims::getSubject); // gives email<br>extractClaim(token, Claims::getExpiration); // gives expiry date</pre><h3>7. Extracting Custom Payloads</h3><pre>private Object extractPayload(String token, String payloadKey){<br>    Claims claim = extractAllPayloads(token);<br>    return claim.get(payloadKey);<br>}</pre><p>If you stored phoneNumber or username inside token payload, you can fetch them here.</p><h3>8. Extracting Email (Subject)</h3><pre>private String extractEmail(String token) {<br>    return extractClaim(token, Claims::getSubject);<br>}</pre><p>This is a shortcut for sub.</p><h3>9. Validating Token</h3><pre>public boolean isTokenValid(String token,  String email) {<br>    final String userEmailFetchedFromToken = extractEmail(token);<br>    return (userEmailFetchedFromToken.equals(email) &amp;&amp; !isTokenExpired(token));<br>}</pre><ul><li>Checks if email matches.</li><li>Checks if token is not expired.</li></ul><p>✅ <strong>Tip:</strong> Use this method in your <strong>authentication filters</strong>.</p><h3>10. Checking Expiry</h3><pre>public boolean isTokenExpired(String token) {<br>    return extractClaim(token, Claims::getExpiration).before(new Date());<br>}</pre><h3>11. Testing at Startup</h3><pre>@Override<br>public void run(String... args) throws Exception {<br>    Map&lt;String,Object&gt; payload = new HashMap&lt;&gt;();<br>    payload.put(&quot;email&quot;,&quot;a@b.c&quot;);<br>    payload.put(&quot;username&quot;,&quot;JSR&quot;);<br>    payload.put(&quot;password&quot;,&quot;a123&quot;);<br>    payload.put(&quot;phoneNumber&quot;,&quot;123456789&quot;);<br>    String jwtToken = generateToken(payload,&quot;a@b.c&quot;);<br>    System.out.println(isTokenValid(jwtToken,&quot;a@b.c&quot;));<br>    System.out.println(&quot;JWT Token: &quot; + jwtToken);<br>    System.out.println(extractPayload(jwtToken,&quot;phoneNumber&quot;));<br>    System.out.println(extractPayload(jwtToken,&quot;email&quot;));<br>    System.out.println(extractClaim(jwtToken,Claims::getSubject));<br>}</pre><p>When the app starts, you’ll see:</p><ul><li>Whether token is valid.</li><li>Full token string.</li><li>Extracted values like phoneNumber, email, sub.</li></ul><h3>⚠️ Common Mistakes to Avoid</h3><p><strong>Short Secret Keys</strong></p><ul><li>HS512 requires at least <strong>64 bytes</strong> secret.</li><li>Use Keys.secretKeyFor(SignatureAlgorithm.HS512) if unsure.</li></ul><p><strong>Mixing up Subject vs Payload</strong></p><ul><li>sub (subject) = main identifier (use email/username).</li><li>Payload = extra info.</li></ul><p><strong>Hardcoding Secrets</strong></p><ul><li>Never keep keys directly in Java code.</li><li>Store them in properties or environment variables.</li></ul><p><strong>Not Handling Expired Tokens</strong></p><ul><li>Always check isTokenExpired() before trusting a token.</li></ul><h3>🚀 Final Thoughts</h3><p>With this setup, you can now:</p><ul><li>Generate secure JWT tokens.</li><li>Store custom payload data.</li><li>Validate tokens safely.</li></ul><p>Next steps?</p><ul><li>Integrate this JwtService into a <strong>Spring Security filter</strong>.</li><li>Protect routes (/api/...) using JWT-based authentication.</li></ul><p>👉 That’s it! You now have a <strong>fully working JWT Service in Spring Boot</strong>.<br> No more confusion about subjects, payloads, or secret key sizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d8ff22c56e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>