<?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 Nandhini S on Medium]]></title>
        <description><![CDATA[Stories by Nandhini S on Medium]]></description>
        <link>https://medium.com/@nandhini_s?source=rss-ead73072b53e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5q2_dBHhYC7TU8T9</url>
            <title>Stories by Nandhini S on Medium</title>
            <link>https://medium.com/@nandhini_s?source=rss-ead73072b53e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandhini_s/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[AI’s Biggest Secret: It CAN’T Solve everything!]]></title>
            <link>https://medium.com/@nandhini_s/ais-biggest-secret-it-can-t-solve-everything-d82a13bd5aef?source=rss-ead73072b53e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d82a13bd5aef</guid>
            <category><![CDATA[number-theory]]></category>
            <category><![CDATA[theory-of-computation]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[rsa]]></category>
            <dc:creator><![CDATA[Nandhini S]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 13:00:50 GMT</pubDate>
            <atom:updated>2025-12-20T13:22:47.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*a0IwUGgAzVLKQezsh9hULA.png" /></figure><p>We live in an era where computers can compose musics, diagnose diseases, and navigate self-driving vehicles. Imagine a world where AI solves everything. It writes perfect code, predicts every market crash, and even crafts flawless strategies for global challenges. We often hear about AI as the “<strong>unbeatable machine</strong>”, destined to crack every problem. It feels like computation is limitless.</p><p>But what if I told you that, at the very foundation of <strong>Theory of Computation</strong>, there exist problems that are not just <em>hard</em>, but fundamentally <em>unsolvable</em>? Problems no algorithm — not even one powered by advanced AI — can ever crack for all cases?</p><p>This isn’t about any tech limitations or AI not being smart enough <em>yet</em>. This is about deep, basic rules of <strong>logic</strong>.</p><p>For every engineer building the future, every DSA enthusiast optimising code, and every student dreaming of innovation, understanding these <strong>“unsolvable” problems</strong> is like knowing the laws of physics for a rocket scientist. It tells us what the universe of computation <em>is</em> and <em>isn’t</em> capable of.</p><p>Let’s dive into these logical walls, meet the smart people who found these unsolvable problems, and see how even the “unsolvable” can help us build “unbreakable” systems.</p><h3>The Halting Problem: The Infinite Loop Puzzle</h3><p>Every programmer would definetly have come accross this infinte loop, made a while(true) loop. Our coding tools can usually spot these simple endless loops.</p><p>But what if the loop isn’t obvious? What if it’s hidden deep within complex logic? This brings us to the heart of the first great mystery: <strong>The Halting Problem.</strong></p><p>Imagine we have a “Loop Detector” program to identify the program which will run into endless loop. Sounds incredibly useful, right? If we had this, we’d never have crashing software! But here’s where the plot thickens…</p><p>Consider a program designed to test <strong>Goldbach’s Conjecture</strong>. This famous math puzzle, from the 1700s, says:</p><blockquote>Every even number bigger than 2 is the sum of two prime numbers.</blockquote><p>Our program would start checking: 4 (2+2), 6 (3+3), 8 (3+5)… <br>If it ever found an even number that <em>couldn’t</em> be made from two primes, it would halt. <br>If Goldbach’s Conjecture is true, it would run into infinite loop.</p><p>Does <em>this</em> program stop? We don’t know! Mathematicians have been trying to prove or disprove Goldbach’s Conjecture for over 280 years. For our “Loop Detector” to predict if this code stops, it would have to solve a math mystery that has stumped humanity for centuries! This shows why the Halting Problem is so tricky.</p><h4>Goldbach &amp; Euler Friendship</h4><p>The very puzzle we just talked about — Goldbach’s Conjecture — was born from an extraordinary friendship between two brilliant minds in the 18th century: <strong>Christian Goldbach</strong> and <strong>Leonhard Euler </strong>(the very one who introduced Euler Theorem/Number Theory).</p><p>In 1742, Goldbach, shared his famous conjecture in a letter to Euler. Their friendship, spanning 35 years and nearly 200 letters, became a vibrant intellectual playground of mathematics. Euler was more interested in physics and calculus. Goldbach actually encouraged Euler to dive deeper into <strong>number theory</strong> — which is foundation of modern internet security (RSA encryption). Their story reminds us that even the most abstract mathematical questions often begin with human curiosity and collaboration.</p><h4>Turing Masterpience: Computation has a limit</h4><p>Fast forward to the 1900s. <strong>Alan Turing</strong> was thinking hard about what computers could and couldn’t do. In 1936, Turing proved that our dream of a perfect “Loop Detector” (the program that solves the Halting Problem) was not just hard, but <strong>logically impossible</strong>. He did this with a stunning <strong>proof by contradiction</strong></p><h4><strong>Proof by Contradiction</strong></h4><p>Imagine we <em>do</em> have that perfect “Loop Detector” program, let’s call it Halt program H. It can look at <em>any</em> program P and its input I, and perfectly declare: “Yes, P stops,” or “No, P runs forever.”</p><pre>H(P, I):<br>  if P halts for given I:<br>    return &quot;Yes&quot;<br>  else<br>    return &quot;No&quot;</pre><p>Now, Turing invented a peculiar program, a mischievous piece of code he called the <strong>“Stubborn Machine” (</strong>Opposite program S<strong>)</strong>.</p><pre>S(O):<br>  if H(O, O) == &quot;Yes&quot;:<br>    loop endlessly<br>  else<br>    halt</pre><ul><li>The Stubborn Machine (S) takes its <em>own code</em> as input (O).</li><li>Then, S feeds its own code to our perfect Loop Detector (H) and asks: <em>“If I run myself, will I stop?”</em></li><li>If H <em>predicts</em> that S will stop, then S is programmed to immediately enter an <strong>endless loop</strong>.</li><li>If H <em>predicts</em> that S will run forever, then S is programmed to <strong>stop right away</strong>.</li></ul><p><strong>The Unavoidable Clash:<br>- </strong>If H says S stops, S actually loops. So H was wrong.<br>- If H says S loops, S actually stops. So H was wrong again.</p><p>If this <strong>Loop Detector</strong> program is really super smart which can solve tricky Halting problem — passing stubborn machine logic to this detector will fails it actual logic. Hence, the program <strong>H</strong> doesn’t exist.</p><p>If you’re finding hard to understand the Proof of Contradiction — will explain using real time scenario:</p><h4>The Barber’s Riddle</h4><p>Imagine a town with a very particular barber. His rule is simple and absolute: <strong>“I shave all those, and only those, who do not shave themselves.”</strong></p><p>Now, ask yourself: <strong>Does the barber shave himself?</strong></p><p><strong>If he shaves himself:</strong> He breaks his own rule! (Because he only shaves people who <em>don’t</em> shave themselves).<br><strong>If he doesn’t shave himself:</strong> His rule says he <em>must</em> shave himself! (Because he shaves everyone who <em>doesn’t</em> shave themselves, and as per the rule he cannot shave on his own).</p><p>Like Turing’s Stubborn Machine, the barber cannot exist without contradicting his own defining rule.</p><p>Some might have thoughts,</p><h4>Why we can’t just “Force it to Halt”</h4><p>If the decider says it will loop, we just halt it instead — is actually what we do in the real world! We use timeouts. If a program runs for 30 seconds and doesn’t finish, we kill it.</p><p>However, in computer science theory, this doesn’t “solve” the problem because:</p><ul><li><strong>False Positives</strong>: Maybe the program was going to finish at 31 seconds with the cure for cancer. By halting it, you changed the outcome.</li><li><strong>The Decider itself might loop</strong>: To decide if a complex program loops, the “Decider” might have to run its own internal simulation that never ends. You would then need a “Decider for the Decider,” leading to an infinite chain of machines.</li></ul><h4>Is there a solution?</h4><p>There is no general solution. We cannot build one single “Judge” that can perfectly analyse every possible piece of code.<br>But we have <strong>Partial</strong> solutions:<br>- Static Analysis: Compilers can find many types of infinite loops before you run the code.<br>- Total Functional Programming: Some specialized languages (like Agda or Coq) are designed so that you cannot write an infinite loop. They force every function to be “total,” meaning it must eventually return a value.</p><h4>Euler’s Number theory: Foundation of RSA encryption</h4><p>So, if some problems are truly impossible for computers, how do we build safe and strong systems? The key is the difference between “<strong>unsolvable</strong>” (can’t ever be figured out) and “<strong>computationally hard</strong>” (can be figured out, but takes too long).</p><p>This is where Euler’s number theory, inspired by Goldbach, comes back in a big way with <strong>RSA Encryption</strong>, which keeps our online transactions safe.</p><h4>How Euler’s Primes Protect Your Data</h4><p>The core idea is simple: Some math is easy to do in one direction, but “impossible” to reverse.</p><ul><li><strong>Easy Part (Multiplication):</strong> If I give you two large prime numbers (let’s call them <em>p</em> and <em>q</em>, it is very easy for a computer to multiply them to get a massive number <em>N</em>.</li></ul><pre>p * q = N</pre><ul><li><strong>The Impossible Part (Factoring): </strong>If I give you the massive number <em>N</em> and ask you, “Which two primes did I multiply to get this?” it becomes a nightmare. <br>For a number with 600 digits, it would take the world’s most powerful supercomputers billions of years to find <em>p</em> and <em>q</em>.</li><li>Where Euler Comes InEuler discovered a special rule (using his Totient Function, 𝜙(𝑛), that allows us to create a <strong>secret trapdoor</strong>.<br>- <strong>The Public Key</strong>: Everyone sees <strong><em>N</em></strong>. They use it to <em>lock</em> a message to you.<br>- <strong>The Private Key</strong>: Because only you know the original primes <em>p</em> and <em>q</em> (thanks to Euler’s formula), you are the only one who can <em>unlock</em> it.</li></ul><p><strong>Halting Problem vs. RSA:</strong></p><ul><li>The Halting Problem is <strong>unsolvable</strong>: It’s logically impossible to solve for all cases.</li><li>RSA uses a problem that is <strong>solvable but computationally hard</strong>: It <em>is</em> logically possible to break (by finding p and q), but it would take so much time that it’s practically impossible to do.</li></ul><p>This <strong>computational hardness</strong> is what makes our internet secure. We build unbreakable systems not by solving the impossible, but by exploiting problems so incredibly difficult to reverse-engineer that they are practically uncrackable.</p><h4>Euler’s Graph theory: Königsberg Bridge Problem</h4><p><strong>Leonhard Euler</strong> proved another impossibility, not with abstract logic, but with a geographical puzzle.</p><p>In the 18th-century city of Königsberg, there were four land areas connected by seven bridges. The citizen had a popular game: “Can you walk through the city, crossing every bridge just once, and end up back where you started?” No one could do it. They asked Euler to prove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*p7wD3hzq2to6qFuGsL1a5g.jpeg" /></figure><h4>How Euler solved it? (The Birth of Graph Theory)</h4><p>Euler realised that the size of the islands and the length of the bridges didn’t matter. He didn’t try every path. He simplified the map into a <strong>graph</strong>: dots (nodes) for land, lines (edges) for bridges.</p><p><strong>The Logic:</strong> If you enter a piece of land by one bridge, you must leave it by another. This means every piece of land (except the start and end) must have an even number of bridges (edges).</p><p><strong>The Proof</strong>: <br>- Island A had 5 bridges.<br>- Island B had 3 bridges.<br>- Island C had 3 bridges.<br>- Island D had 3 bridges.</p><p><strong>The Conclusion</strong>: Since there were four locations with an odd number of bridges, the walk was mathematically impossible. You can’t have four “start or end” points!</p><h4>Quiz Time</h4><p>Let’s see if you can use Euler’s logic to solve this. Imagine a small park with four islands and a series of bridges.</p><p><strong>Challenge:</strong> Your goal is to <strong>cross every bridge exactly once</strong>. You can start anywhere, but you cannot “fly” or “swim” — you must use the bridges.</p><p><strong>Map</strong>:<br>- Island A has 3 bridges.<br>- Island B has 2 bridges.<br>- Island C has 3 bridges.<br>- Island D has 2 bridges.</p><p><strong>Question<br></strong>Based on Euler’s “Bridge Logic” (the number of bridges connected to each island), is this path possible?<br><strong>Hint</strong>: The “In-and-Out” Rule<br>Remember what Euler discovered:</p><ul><li>If you pass through an island, you use <strong>one bridge to enter</strong> and <strong>one bridge to leave</strong> (that’s 2 bridges).</li><li>The only islands that can have an <strong>odd</strong> number of bridges are your <strong>Starting Point</strong> and your <strong>Ending Point</strong>.</li><li>Every other island <strong>must</strong> have an <strong>even</strong> number of bridges.</li></ul><p>Take a look at the bridge counts above. Does this map meet Euler’s requirement for a successful walk? Comment down the answer under my blog and also mention what are the DSA algorithms which uses this graph theory as it’s foundation?</p><p>The stories of Goldbach, Euler, and Turing are more than just old tales. They are powerful lessons in <strong>how computers truly work</strong>.</p><p>Their insights teach us: understanding what computers <em>cannot</em> do is just as important as understanding what they <em>can</em> do. It helps us build stronger systems, find problems that truly can’t be solved, and appreciate the clever ways we use these limits to our advantage.</p><p>The next time you’re amazed by a computer or an AI, remember those invisible logical walls. In those walls, strangely enough, lies both the elegance of pure mathematics.</p><p>This is just the beginning! If you found this dive into computation’s fundamental limits exciting, stay tuned for detailed blogs on <strong>RSA encryption concepts</strong> — exploring how Euler’s number theory makes our digital world secure — and practical <strong>DSA algorithms that use graph theory</strong> for everything from network analysis to pathfinding. Follow along as we continue to bridge the amazing gap between abstract math and real-world computer science!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d82a13bd5aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Security: JWT Authentication & Role Based Access]]></title>
            <link>https://medium.com/@nandhini_s/spring-boot-security-jwt-authentication-role-based-access-34fed9b0b657?source=rss-ead73072b53e------2</link>
            <guid isPermaLink="false">https://medium.com/p/34fed9b0b657</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[role-based-authorization]]></category>
            <dc:creator><![CDATA[Nandhini S]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 13:48:56 GMT</pubDate>
            <atom:updated>2025-12-12T05:48:55.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot Security: JWT Authentication &amp; Role Based Authorization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P1-zlq-V1alA4FrkmltRg.jpeg" /></figure><p>Ever wondered how websites and apps keep your data safe and ensure only the right people can access certain features? In the world of Spring Boot APIs, two powerful tools stand out: <br><strong>- JSON Web Tokens (JWT)<br>- Role-Based Access Control (RBAC)</strong></p><p>Before we dive into the code, let’s understand fundamental security concepts:</p><h4><strong>Authentication:</strong></h4><p><strong><em>“Who are you?”</em></strong><br>This is the process of verifying a user’s identity. When you log in with a username and password, the system is <em>authenticating</em> you. It’s checking if you are who you claim to be.</p><h4><strong>Authorization:</strong></h4><p><strong><em>“What are you allowed to do?”</em></strong><br>Once you’re authenticated (your identity is confirmed), <em>authorization</em> determines what resources or actions you’re permitted to access.</p><p>Now, let’s see how JWT and RBAC fit into these concepts:</p><h4>Why JWT?</h4><p>Traditionally, web applications used “sessions” for security. When you logged in, the server created a session, stored some info about you, and gave your browser a “session ID” (usually in a cookie). For every subsequent request, your browser sent the session ID (STATEFUL), and the server looked up your session.</p><p>JWTs offer a <strong>STATELESS</strong> way to handle authentication. Instead of the server remembering your session, the <em>token itself</em> contains all the necessary information about you (like your username and roles).</p><h4><strong>JWT (JSON Web Token) Authentication</strong></h4><ul><li>JWTs are used for securely transmitting claims/information between parties. These Claims are name or value pairs that relay facts about the token subject that communicate identity and authorization details.</li><li>JWT token made up of three elements, separated by dots (.): a <strong>header</strong>, <strong>payload</strong>, and a <strong>signature</strong>.</li><li>A JWT token looks like three base64-encoded strings separated by dots: xxxxx.yyyyy.zzzzz</li></ul><h4>1. Header (xxxxx)</h4><p>The header typically consists of two parts: the type of the token (which is JWT) and the signing algorithm being used (e.g., HS256).</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li><strong>alg (Algorithm):</strong> Indicates the cryptographic algorithm used to sign the JWT. Common choices are HMAC SHA256 (HS256) or RSA (RS256).</li><li><strong>typ (Type):</strong> Declares the type of the token, which is usually JWT.</li></ul><h4>2. Payload (yyyyy)</h4><p>The payload contains the <strong>actual claims</strong> about the user and the token.</p><pre>{<br> &quot;sub&quot;: &quot;username&quot;,<br> &quot;role&quot;: [&quot;ADMIN&quot;],<br> &quot;iat&quot;: 1678886400,<br> &quot;exp&quot;: 1678972800<br>}</pre><ul><li><strong>sub (Subject):</strong> Identifies the <strong>principal</strong> (user) that is the subject of the JWT.</li><li><strong>exp (Expiration Time):</strong> The time after which the JWT must not be accepted for processing. This is crucial for security, limiting the window an attacker has if a token is stolen.</li><li><strong>iat (Issued At):</strong> The time at which the JWT was issued. Useful for determining token age.</li><li><strong>Custom Claims:</strong> You can add any custom data relevant to your application, such as role (as in our example), user ID, email, etc. This is how RBAC information is carried within the token.</li></ul><h4>3. Signature (zzzzz)</h4><p>The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message hasn’t been changed along the way.</p><pre>HMACSHA256(<br> base64UrlEncode(header) + “.” +<br> base64UrlEncode(payload),<br> secret-key-a-string-secret-at-least-256-bits-long<br>)</pre><p>The server uses a secret key to create and verify the signature. Only the server (or other authorised parties with the secret key) can generate a valid signature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Y4_3b__74O6lxuxiZco_g.png" /></figure><h4><strong>RBAC (Role-Based Access Control) Authorization</strong></h4><ul><li>RBAC restricts system access by assigning users roles, which are then granted specific permissions.</li><li>Users receive roles (e.g., ADMIN, USER). Each role has defined permissions for actions/resources. During authorization, the system checks if the authenticated user’s role(s) have the required permissions for the requested operation (e.g., via <strong>@PreAuthorize</strong> in Spring Security).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*U062dpMYIQyff_-wmYLQuA.png" /></figure><p>Now that we’ve covered the theoretical foundations and understood the required dependencies, it’s time to get our hands dirty and bring this secure application to life.</p><h4>Architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wV9hHFgiwWWpIovGxGIZA.png" /></figure><ul><li><strong>Controller:</strong> Receives HTTP requests (like login) and orchestrates API responses.</li><li><strong>Security Filter Chain:</strong> Ordered sequence of security checks that every request passes before business logic.</li><li><strong>AuthenticationFilter:</strong> Intercepts incoming HTTP requests to validate JWTs and set the authenticated user’s context.</li><li><strong>SecurityContextHolder:</strong> Stores the currently authenticated user’s details and roles for the duration of a request.</li><li><strong>AuthenticationEntryPoint:</strong> Handles what happens when an unauthenticated user tries to access a protected resource (sends a 401 Unauthorized). Handle error/exception occurs during authentication</li><li><strong>AuthenticationManager:</strong> Coordinates the authentication process by delegating to providers.</li><li><strong>AuthenticationProvider:</strong> Performs the actual verification of user credentials (username/password).</li><li><strong>PasswordEncoder:</strong> Securely hashes and compares user passwords.</li><li><strong>SecurityConfig:</strong> Custom Central configuration for Spring Security, defining rules, filters, and beans like AuthenticationManager and PasswordEncoder</li><li><strong>JwtUtil /JwtService:</strong> It’s responsible for <strong>generating</strong> new tokens after successful login, and <strong>validating</strong> existing tokens (checking signature, expiration) and <strong>extracting</strong> user information (like username and roles) from them during protected API calls.</li></ul><h4>Project Structure</h4><pre>com.example<br>├── controller<br>│ └── AuthController<br>├── exception<br>│ └── CustomException<br>├── model<br>│ ├── Role<br>│ └── User<br>├── repository<br>│ ├── RoleRepository<br>│ └── UserRepository<br>├── security<br>│ ├── jwt<br>│ │ ├── AuthEntryPoint<br>│ │ ├── AuthTokenFilter<br>│ │ └── JwtService<br>│ └── service<br>│ └── UserDetailsServiceImpl<br>│ └── SecurityConfig<br>└── JwtdemoApplication</pre><p>Let’s start coding!</p><h4>Project Setup</h4><ul><li>Go to <strong>Spring Initializr (</strong><strong>start.spring.io)<br></strong><em>Primary tool for setting up a Spring Boot project. It includes all the common, essential Spring-related dependencies.</em></li><li>Set <strong>Maven</strong>, <strong>Java 17</strong>, <strong>Spring Boot (latest stable)</strong>.</li><li>Add these dependencies: Spring Web, Spring Data JPA, Spring Security, H2 Database.</li><li>Click “Generate” and download the project. Extract the downloaded project and import it into your IDE</li><li>Open pom.xml</li><li>Inside the &lt;dependencies&gt; section, manually add the jjwt-api, jjwt-impl (runtime scope), and jjwt-jackson (runtime scope) dependencies. Use highly version — get it from maven repository site.</li></ul><p>Before we dive into the individual code files, let’s visualize how these components interact during the two main scenarios: a user logging in and then accessing a protected resource.</p><p><strong>1. User Login (Authentication — “Who are you?”)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMbh-scThO8g7LEFY9sNLw.png" /></figure><h4>2. Accessing Protected Resources (Authorization — “What are you allowed to do?”)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPLnuRzBmXuWvX-rk_ITeA.png" /></figure><p>Let’s walk through each file in your project structure and understand its specific role in building our secure Spring Boot application.</p><p>JwtdemoApplication.java</p><p>This is the main <strong>entry point</strong> of your Spring Boot application.</p><pre><br>package com.example;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;ja<br><br>@SpringBootApplication<br>public class JwtdemoApplication {<br><br> public static void main(String[] args) {<br>        SpringApplication.run(JwtdemoApplication.class, args);<br> }<br>}</pre><p><strong>@SpringBootApplication</strong>: This annotation is the heart of your Spring Boot application, combining @Configuration, @EnableAutoConfiguration, and @ComponentScan. It tells Spring Boot how to configure itself and where to find other components.</p><p>When you begin coding, it’s best to start with the most foundational components and build upwards.</p><h4>1. Models</h4><p>First, we define our core data structures: Role and User.</p><p>model/Role.java</p><pre>package com.example.model;<br><br>import jakarta.persistence.*;<br><br>@Entity<br>public class Role {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br>    @Column(unique = true)<br>    private String roleName;<br>    // Constructors (Role(), Role(String roleName), Role(int id, String roleName))<br>    // Getters and Setters for id, roleName<br>}</pre><p>model/User.java</p><pre>package com.example.model;<br><br>import jakarta.persistence.*;<br>import org.jspecify.annotations.Nullable;<br>import org.springframework.security.core.GrantedAuthority;<br>import org.springframework.security.core.authority.SimpleGrantedAuthority;<br>import org.springframework.security.core.userdetails.UserDetails;<br><br>import java.util.Collection;<br>import java.util.Set;<br><br>@Entity<br>public class User implements UserDetails {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br>    private String username;<br>    @Column(unique = true)<br>    private String email;<br>    private String password;<br>    @ManyToOne(fetch = FetchType.EAGER)<br>    @JoinColumn(name=&quot;role_id&quot;, referencedColumnName = &quot;id&quot;)<br>    private Role role;<br><br>    // Constructors (User(), User(String username, String email, String password), etc.)<br>    // Getters and Setters for id, username, email, password, role<br><br>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>        return Set.of(new SimpleGrantedAuthority(&quot;ROLE_&quot; + this.role.getRoleName()));<br>    }<br><br>    @Override<br>    public @Nullable String getPassword() {<br>        return this.password;<br>    }<br><br>    @Override<br>    public String getUsername() {<br>        return this.username;<br>    }<br>}</pre><ul><li><strong>@Entity</strong>: Marks this class as a JPA entity, indicating that it maps directly to a table in your database.</li><li><strong>@Id</strong>: Designates the id field as the primary key for the Role table.</li><li><strong>@GeneratedValue(strategy = GenerationType.IDENTITY)</strong>: Configures the id to be automatically generated by the database (e.g., auto-increment).</li><li><strong>@Column(unique = true)</strong>: Ensures that the roleName (e.g., &quot;ADMIN&quot;, &quot;USER&quot;) is unique across all roles in the database, preventing duplicate role entries.</li><li><strong>@ManyToOne(fetch = FetchType.EAGER)</strong>: Defines a many-to-one relationship with the Role entity. This means multiple User records can be associated with a single Role. FetchType.EAGER ensures the Role is loaded immediately when a User is retrieved.</li><li><strong>@JoinColumn(...)</strong>: Specifies the foreign key column (role_id) in the Role table that links to the primary key (id) of the User table.</li><li><strong>implements UserDetails</strong>: This is crucial! By making your User class implement this interface, you&#39;re telling Spring Security, &quot;Hey, this is how you get all the essential information about my users.&quot;</li><li><strong>getAuthorities()</strong>: This method tells Spring Security what <strong>roles</strong> (like &quot;ADMIN&quot; or &quot;USER&quot;) this user has. Spring Security uses these roles to decide what the user is allowed to do.</li></ul><h4>2. Repositories</h4><p>Next, we define our JPA repository interfaces to interact with the database for Role and User entities.</p><p>repository/RoleRepository.java</p><pre>package com.example.respository;<br><br>import com.example.model.Role;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.Optional;<br><br>@Repository<br>public interface RoleRepository extends JpaRepository&lt;Role, Integer&gt; {<br><br>    Optional&lt;Role&gt; findByRoleName(String user);<br>}</pre><p>repository/UserRepository.java</p><pre>package com.example.respository;<br><br>import com.example.model.User;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.Optional;<br><br><br>@Repository<br>public interface UserRepository  extends JpaRepository&lt;User, Integer&gt; {<br>    Optional&lt;User&gt; findByUsername(String username);<br>}</pre><ul><li>@Repository: Marks this as a Spring Data JPA repository.</li><li>extends JpaRepository&lt;T, ID&gt;: Provides standard CRUD operations for the entity.<br>Imagine you&#39;re building a website or an API. You need to know:</li></ul><h4>3. User Details Service</h4><p>This service act as the bridge between your user data and the security framework.</p><pre>package com.example.security.service;<br><br>import com.example.model.User;<br>import com.example.respository.UserRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class UserDetailsServiceImpl implements UserDetailsService {<br>    @Autowired<br>    UserRepository userRepository;<br>    @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>       return user;<br>    }<br>}</pre><ul><li>@Service: Marks this class as a Spring service component, making it eligible for dependency injection.</li></ul><h4>4. JWT Utility Service</h4><p>This service handles all operations related to generating, validating, and extracting information from JWTs.</p><p>application.properties</p><pre># Custom property for JWT token processing<br>jwt.secretKey=ThisIsASecretKeyThisIsASecretKeyThisIsASecretKey<br>jwt.expiry=86400000</pre><p>security/jwt/JwtService.java</p><pre>package com.example.security.jwt;<br><br><br>import com.example.model.User;<br>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import io.jsonwebtoken.io.Decoders;<br>import io.jsonwebtoken.security.Keys;<br>import io.jsonwebtoken.security.WeakKeyException;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.GrantedAuthority;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.stereotype.Component;<br><br>import javax.crypto.SecretKey;<br>import java.util.Date;<br>import java.util.List;<br><br>@Component<br>public class JwtService {<br>    // generateJwtToken on successful login<br>    @Value(&quot;${jwt.secretKey}&quot;)<br>    private String secretKey;<br>    @Value(&quot;${jwt.expiry}&quot;)<br>    private long expiration;<br>    public SecretKey getKey(){<br>        byte[] key = Decoders.BASE64.decode(secretKey);<br>        if(key.length&lt;32){<br>            throw new WeakKeyException(&quot;Secret key must be at least 32 characters long&quot;);<br>        }<br>        return Keys.hmacShaKeyFor(key);<br>    }<br>    public String generateJwtToken(Authentication authentication){<br>        User user = (User) authentication.getPrincipal();<br>        List&lt;String&gt; roles = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();<br>        return Jwts.builder()<br>                .setSubject(user.getUsername()).claim(&quot;role&quot;, roles)<br>                .setIssuedAt(new Date(System.currentTimeMillis()))<br>                .setExpiration(new Date(System.currentTimeMillis()+expiration))<br>                .signWith(getKey(), SignatureAlgorithm.HS256).compact();<br>    }<br>    // validateToken and get info from token<br>    public Claims extractAllClaims(String token){<br>        return Jwts.parser()<br>                .setSigningKey(getKey())<br>                .build()<br>                .parseClaimsJws(token)<br>                .getBody();<br>    }<br>    public String extractUsername(String token){<br>        Claims claims = extractAllClaims(token);<br>        return claims.getSubject();<br>    }<br>    public Date extractExpiry(String token){<br>        Claims claims = extractAllClaims(token);<br>        return claims.getExpiration();<br>    }<br>    public boolean validateJwtToken(String token, UserDetails userDetails){<br>        return (extractUsername(token).equals(userDetails.getUsername()) &amp;&amp;<br>                !extractExpiry(token).before(new Date(System.currentTimeMillis())));<br>    }<br>}</pre><ul><li>@Component: Marks this class as a Spring component, making it available for dependency injection.</li><li>@Value(&quot;${jwt.secretKey}&quot;), @Value(&quot;${jwt.expiry}&quot;): These annotations inject values from your application.properties file. jwt.secretKey is the secret string used to sign and verify JWTs, and jwt.expiry is the token&#39;s validity duration in milliseconds.</li><li>getKey(): This method decodes the base64-encoded secretKey and generates a SecretKey object, which is essential for jjwt to sign and verify tokens. It also includes a check to ensure the key is sufficiently long for strong cryptography.</li><li>generateJwtToken(Authentication authentication): This is called after a user successfully authenticates. It creates a new JWT, setting the user&#39;s username as the subject (sub), adding their roles as a custom role claim, and defining the token&#39;s issuance (iat) and expiration (exp) times. It then signs the token using your secret key.</li><li>extractAllClaims(String token): This method parses a given JWT using your secret key and returns all the claims (the payload) contained within it.</li><li>extractUsername(String token), extractExpiry(String token): Helper methods to easily retrieve the username (subject) and expiration date from a token&#39;s claims.</li><li>validateJwtToken(String token, UserDetails userDetails): This crucial method verifies the validity of a JWT. It checks two main things:<br>- Does the username extracted from the token match the username of the provided UserDetails?<br>- Has the token expired?</li></ul><h4>5. Auth Entry Point</h4><p>This component is Spring Security’s way of handling unauthorised requests, providing a custom and user-friendly error response when an unauthenticated user tries to access a protected resource.</p><p>security/jwt/AuthEntryPoint.java</p><pre>package com.example.security.jwt;<br><br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import org.springframework.security.core.AuthenticationException;<br>import org.springframework.security.web.AuthenticationEntryPoint;<br>import org.springframework.stereotype.Component;<br><br>import java.io.IOException;<br><br>@Component<br>public class AuthEntryPoint implements AuthenticationEntryPoint {<br>    @Override<br>    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {<br>        response.setContentType(&quot;application/json&quot;);<br>        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);<br>        response.getWriter().write(&quot;{\&quot;message\&quot;: \&quot;Unauthorized access.\&quot;, \&quot;status\&quot;: 401}&quot;);<br>    }<br>}</pre><ul><li>implements AuthenticationEntryPoint: This Spring Security interface is invoked whenever an unauthenticated user attempts to access a protected resource. Instead of a default browser login prompt or a generic error, this allows you to customize the response.</li><li>commence(...): This method is called by Spring Security in such scenarios. It sets the HTTP response status to 401 UNAUTHORIZED and writes a custom JSON error message to the response body, providing clear feedback to the client.</li></ul><h4>6. Auth Token Filter</h4><p>This is custom filter that intercepts all incoming HTTP requests to validate JWTs and establish the user’s SecurityContext.</p><p>security/jwt/AuthTokenFilter.java</p><pre>package com.example.security.jwt;<br><br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br><br>import java.io.IOException;<br><br>@Component<br>public class AuthTokenFilter extends OncePerRequestFilter {<br>    @Autowired<br>    JwtService jwtService;<br>    @Autowired<br>    UserDetailsService userDetailsService;<br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<br>        String authHeader = request.getHeader(&quot;Authorization&quot;);<br>        if (authHeader != null &amp;&amp; authHeader.startsWith(&quot;Bearer &quot;)) {<br>            // TODO: validate token<br>            String token = authHeader.substring(7);<br>            UserDetails userDetails = userDetailsService.loadUserByUsername(jwtService.extractUsername(token));<br>            if (jwtService.validateJwtToken(token, userDetails)) {<br>                if(userDetails != null &amp;&amp; jwtService.validateJwtToken(token, userDetails)){<br>                    UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken.authenticated(userDetails, null, userDetails.getAuthorities());<br>                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));<br>                    SecurityContextHolder.getContext().setAuthentication(authentication);<br>                }<br>            }<br>        }<br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><ul><li>extends OncePerRequestFilter: This ensures that the filter is executed exactly once for each incoming HTTP request, which is ideal for JWT validation.</li><li>doFilterInternal(...): This method contains logic for JWT processing for every request:<br>- It inspects the Authorization header for a Bearer token.<br>- If found, it extracts the JWT and then uses JwtService to extract the username.<br>- It then uses UserDetailsService to load the full UserDetails for that username from your database.<br>- It calls JwtService.validateJwtToken() to verify the token&#39;s authenticity and expiration.<br><strong>Crucially: </strong><br>- If the token is valid, it creates a UsernamePasswordAuthenticationToken and sets it in the SecurityContextHolder. This action tells Spring Security that the current request is authenticated, and it provides the user&#39;s identity and roles for subsequent authorization checks.</li><li>filterChain.doFilter(...) passes the request to the next filter in Spring Security&#39;s chain.</li></ul><h4>7. Security Configuration</h4><p>This is to define the security rules, enable features, and wire up your custom components.</p><p>security/SecurityConfig.java</p><pre>package com.example.security;<br><br>import com.example.security.jwt.AuthEntryPoint;<br>import com.example.security.jwt.AuthTokenFilter;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;<br>import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>@Configuration<br>@EnableWebSecurity<br>@EnableMethodSecurity<br>public class SecurityConfig {<br>    @Autowired<br>    AuthTokenFilter authTokenFilter;<br>    @Autowired<br>    AuthEntryPoint jwtAuthenticationEntryPoint;<br>    @Bean<br>    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {<br>        return authConfig.getAuthenticationManager();<br>    }<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        return http.cors(cors-&gt;cors.disable())<br>                .csrf(csrf -&gt; csrf.disable())<br>                .sessionManagement(session-&gt;session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br>                .authorizeHttpRequests(auth -&gt; auth<br>                        .requestMatchers(&quot;/api/**&quot;).permitAll()<br>                        .anyRequest().authenticated()<br>                )<br>                .exceptionHandling(exception -&gt; exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))<br>                .addFilterBefore(authTokenFilter, UsernamePasswordAuthenticationFilter.class)<br>                .build();<br>    }<br>}</pre><ul><li>@EnableWebSecurity: Turns on Spring Security for your web application.</li><li>@EnableMethodSecurity: Activates @PreAuthorize annotations, letting you define role-based access directly on controller methods.</li><li>@Bean AuthenticationManager: Central component that handles user authentication requests.</li><li>@Bean PasswordEncoder: Configures the secure way to encrypts and verifies passwords.</li><li>@Bean SecurityFilterChain: This is your main security rulebook for HTTP requests:<br>- cors().disable() / csrf().disable(): Disables CORS and CSRF (common for stateless JWT APIs).<br>- sessionManagement().sessionCreationPolicy(STATELESS): Tells Spring Security not to use sessions, which is essential for JWT.<br>- authorizeHttpRequests(): Defines access rules for endpoint<br>- exceptionHandling(): Uses AuthEntryPoint to send custom 401 Unauthorized errors.<br>- addFilterBefore(): Crucially, inserts your AuthTokenFilter early in the security chain to validate JWTs on every request.</li></ul><h4>8. Controllers</h4><p>This controller handles the login endpoint and exposes various test endpoints with role-based access.</p><p>controller/AuthController.java</p><pre>package com.example.controller;<br><br>import com.example.model.User;<br>import com.example.security.jwt.JwtService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.security.access.prepost.PreAuthorize;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class AuthController {<br>    @Autowired<br>    AuthenticationManager authenticationManager;<br>    @Autowired<br>    JwtService jwtService;<br>    @PostMapping(&quot;/jwt/auth/login&quot;)<br>    public ResponseEntity&lt;?&gt; login(@RequestBody User user){<br>        Authentication authUser = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));<br>        Map&lt;String, String&gt; response = new HashMap&lt;&gt;();<br>        response.put(&quot;token&quot;, jwtService.generateJwtToken(authUser));<br>        response.put(&quot;message&quot;, &quot;Login Successful&quot;);<br>        return ResponseEntity.ok(response);<br>    }<br>    @GetMapping(&quot;/test/all&quot;)<br>    public String allAccess() {<br>        return &quot;Public Content.&quot;;<br>    }<br><br>    @GetMapping(&quot;/test/user&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;) or hasRole(&#39;MODERATOR&#39;) or hasRole(&#39;ADMIN&#39;)&quot;)<br>    public String userAccess() {<br>        return &quot;User Content (accessible by USER, MODERATOR, ADMIN).&quot;;<br>    }<br><br>    @GetMapping(&quot;/test/mod&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;MODERATOR&#39;)&quot;)<br>    public String moderatorAccess() {<br>        return &quot;Moderator Board (accessible by MODERATOR only).&quot;;<br>    }<br><br>    @GetMapping(&quot;/test/admin&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>    public String adminAccess() {<br>        return &quot;Admin Board (accessible by ADMIN only).&quot;;<br>    }<br><br>}</pre><ul><li>@RestController: Combines @Controller and @ResponseBody, indicating that this class handles REST requests and returns data directly as the response body.</li><li>@RequestMapping(&quot;/api&quot;): Sets the base path for all endpoints in this controller to /api.</li><li>@PostMapping(&quot;/jwt/auth/login&quot;):<br>- Handles login requests (username/password).<br>- Authenticates the user via AuthenticationManager.<br>- On success, generates a JWT using JwtService and returns it.</li><li>@GetMapping(&quot;/test/all&quot;): A publicly accessible endpoint.</li><li>@GetMapping(&quot;/test/user&quot;), @GetMapping(&quot;/test/mod&quot;), @GetMapping(&quot;/test/admin&quot;):<br>These endpoints use @PreAuthorize(&quot;hasRole(&#39;ROLE_NAME&#39;)&quot;) to enforce role-based access.</li></ul><h4>10. Exception Handling</h4><p>This global exception handler provides consistent error responses for specific exceptions across your application.</p><p>exception/CustomException.java</p><pre>package com.example.exception;<br><br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.security.authentication.BadCredentialsException;<br>import org.springframework.web.bind.annotation.ControllerAdvice;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.context.request.WebRequest;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>@ControllerAdvice<br>public class CustomException {<br>    // This specific exception is thrown by AuthenticationManager for wrong password<br>    @ExceptionHandler(BadCredentialsException.class)<br>    public ResponseEntity&lt;?&gt; badCredentialsException(BadCredentialsException ex, WebRequest request) {<br>        Map&lt;String, String&gt; errorResponse = new HashMap&lt;&gt;();<br>        errorResponse.put(&quot;error&quot;, &quot;Unauthorized&quot;);<br>        errorResponse.put(&quot;message&quot;, &quot;Invalid username or password.&quot;);<br>        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);<br>    }<br>    // Catch any unexpected errors during the process<br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;?&gt; generalException(Exception e, WebRequest request){<br>        Map&lt;String, String&gt; errorResponse = new HashMap&lt;&gt;();<br>        errorResponse.put(&quot;error&quot;, &quot;Internal Server Error&quot;);<br>        errorResponse.put(&quot;message&quot;, &quot;An unexpected error occurred: &quot; + e.getMessage());<br>        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);<br>    }<br>}</pre><ul><li>@ControllerAdvice: is to centralize exception handling. Instead of adding try-catch blocks in every controller method, you can define methods within a @ControllerAdvice class annotated with @ExceptionHandler to handle specific exception types.</li></ul><p>Lets add ApplicationRunner Bean to pre-populate your database with initial roles and users, which is very helpful for getting started quickly.<br>This method defines a Spring Bean that runs automatically once the application starts</p><p>JwtdemoApplication.java</p><pre>@Bean<br>public ApplicationRunner initData(RoleRepository roleRepository, UserRepository userRepository, PasswordEncoder passwordEncoder) { // Changed interface<br>    return args -&gt; { // Changed parameter type<br>        if (roleRepository.findByRoleName(&quot;USER&quot;).isEmpty()) {<br>            roleRepository.save(new Role(&quot;USER&quot;));<br>            System.out.println(&quot;Created USER&quot;);<br>        }<br>        if (roleRepository.findByRoleName(&quot;MODERATOR&quot;).isEmpty()) {<br>            roleRepository.save(new Role(&quot;MODERATOR&quot;));<br>            System.out.println(&quot;Created MODERATOR&quot;);<br>        }<br>        if (roleRepository.findByRoleName(&quot;ADMIN&quot;).isEmpty()) {<br>            roleRepository.save(new Role(&quot;ADMIN&quot;));<br>            System.out.println(&quot;Created ADMIN&quot;);<br>        }<br><br>        if (userRepository.findByUsername(&quot;admin&quot;).isEmpty()) {<br>            User adminUser = new User(&quot;admin&quot;, &quot;admin@example.com&quot;, passwordEncoder.encode(&quot;adminpass&quot;));<br>            roleRepository.findByRoleName(&quot;ADMIN&quot;).ifPresent(adminUser::setRole);<br>            userRepository.save(adminUser);<br>            System.out.println(&quot;Admin user created: admin/adminpass&quot;);<br>        }<br><br>        if (userRepository.findByUsername(&quot;user&quot;).isEmpty()) {<br>            User regularUser = new User(&quot;user&quot;, &quot;user@example.com&quot;, passwordEncoder.encode(&quot;userpass&quot;));<br>            roleRepository.findByRoleName(&quot;USER&quot;).ifPresent(regularUser::setRole);<br>            userRepository.save(regularUser);<br>            System.out.println(&quot;Regular user created: user/userpass&quot;);<br>        }<br>    };<br>}</pre><p>Other ways are also there to intiate the user first before going forward with login — few options are to create signup api to save it to JPA repository or write sql scripts or use junits.</p><p>Lets test the code we written so far using postman now. Run the JwtDemoApplication class and localhost server will be up and running. Got to postman and start testing.</p><h4>Login</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Itqs_XQYs67vqerz--LorA.png" /></figure><h4>Access Protected Resource</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atvbaqHGGyiMKuwe63Qo_Q.png" /></figure><p>Phew! What a journey. You’ve just mastered the art of securing your Spring Boot APIs with <strong>JWT Authentication</strong> and <strong>Role-Based Access Control</strong>. From the fundamental “who are you?” to the precise “what can you do?”, your application now stands fortified.</p><p>You’ve coded the models, built the stateless security layers. So go forth, build amazing things, and remember: <strong>a secure API is a happy API!</strong></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34fed9b0b657" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>