This is a personal blog for referencing the coding programs. Visitors may not find anything else , but boring & unpleasant code programs which I will be posting for my own reference
Spring Boot - Part 4 (Spring Security & JWT, Lombok, Actuators)
Get link
Facebook
X
Pinterest
Email
Other Apps
Spring Security + JWT
Spring Security adds a gatekeeper in front of your entire application. Every request passes through it before reaching your controllers. You define rules — which endpoints are open to everyone and which require the caller to prove their identity first.
JWT is how users prove their identity on every request. Instead of sending email and password on every request the user logs in once, gets a token, and sends that token with every subsequent request. The server reads the token and knows exactly who the user is.
Together they work like a concert venue:
SpringSecurity= the security system of the venue
JWT = the wristband you get at the entrance
You prove your identity once at the entrance (login), get a wristband (JWT token), and use that wristband to access different areas (protected endpoints) without proving your identity again.
# How JWT Authentication Works in Spring Boot
Step 1 — User sends email and password to POST /auth/login
↓
Step 2 — Server verifies credentials against database
↓
Step 3 — Valid → Server generates JWT token and sends it back
↓
Step 4 — User stores the token
↓
Step 5 — User sends token with every request:
Authorization: Bearer eyJhbGci...
↓
Step 6 — JwtFilter reads and validates token on every request
↓
Step 7 — Valid token → Spring Security knows who the user is
↓
Step 8 — SecurityConfig rules decide if user can access endpoint
↓
Step 9 — Request reaches controller or gets blocked with 403
The 6 Components of Spring Security & JWT
1] JwtService (The Brain)
This is the brain of the entire JWT system. It is a utility class that knows how to do 3 things:
Generate a token — when a user logs in successfully, you call this to create a JWT token for them containing their email and expiry time
Extract email from token — when a request comes in with a token, you call this to find out who the user is
Validate a token — checks if the token is genuine and not expired
Why it matters: Every other component depends on this class. It's the foundation that makes JWT work in your application.
Technical details:
Uses a secret key to sign tokens (prevents tampering)
Tokens contain: subject (email), issued at, expiration time
Can add custom claims (roles, user ID, etc.)
2] JwtFilter (The Checkpoint Guard)
This is the first line of defense that intercepts every incoming request. Think of it as the security guard at the venue entrance who checks everyone's wristband. If you've used middleware in Node.js, you already understand JwtFilter! It's the exact same concept with different syntax.
What it does on every request:
Looks for the wristband — extracts the Authorization header and checks if it starts with "Bearer "
If no wristband — lets the request pass through to SecurityConfig (which may allow or deny based on public endpoints)
If wristband exists — calls JwtService to:
Extract the email from the token
Validate if token is genuine and not expired
If valid — creates an Authentication object and places it in Spring Security's SecurityContext (like telling the security system "this person is verified")
If invalid — token is rejected and request never reaches controllers
Key Insight: Without this filter, Spring Security would never know about your JWT system. It's the bridge that connects your custom JWT logic to Spring Security's internal authentication system.
Why it extends OncePerRequestFilter: Ensures the filter executes exactly once per request, not multiple times if you have filter chains.
NOTE : The JWTFilter is just a simple middleware that we register inside SecurityConfig file instead of "app.use()" like in Nodejs. In Nodejs you build the filter chain from scratch with app.use(), Spring has 15+ built-in filters; you insert yours at specific positions.
3] UserDetailsService (The Identity Database Lookup)
This is Spring Security's way of finding who a user is. It's like the venue's customer database.
What it does:
Takes an email (extracted from JWT or login request)
Queries your database to find the user
Returns a UserDetails object containing:
Email/username
Password (stored encrypted)
Roles/permissions (e.g., ROLE_USER, ROLE_ADMIN)
Why it's needed: Spring Security doesn't know how your users are stored. This interface tells it how to load user information from YOUR database structure.
4] AuthenticationManager (The ID Checker)
This component handles the actual login process. It's the security guard at the entrance who checks your ID before giving you a wristband.
What it does only at login (/auth/login):
Receives email + password
Calls UserDetailsService to fetch the user
Compares provided password with stored password (using PasswordEncoder)
If match → authentication succeeds
If mismatch → throws exception (401 Unauthorized)
Why separate from JwtFilter:
JwtFilter handles requests after user has wristband
AuthenticationManager handles requests to get the wristband
Behind the scenes:AuthenticationManager is actually an interface. Spring Boot auto-configures a default implementation that uses DaoAuthenticationProvider, which in turn uses your UserDetailsService and PasswordEncoder.
5] SecurityConfig (The Venue Rulebook)
This is where you define who can go where. It's the overall security policy of your venue.
Two main things it does:
A) Defines endpoint access rules:
/auth/** → Open to everyone (entrance area)
/api/user/** → Requires USER role (general admission)
/api/admin/** → Requires ADMIN role (backstage pass)
/swagger-ui/** → Open (public documentation)
B) Configures security behavior:
Stateless sessions — tells Spring Security "don't create sessions, we're using JWT"
Disable CSRF — because JWT is stateless, CSRF protection isn't needed
Adds JwtFilter — inserts your custom filter before Spring Security's default authentication
Important: Even if JwtFilter sets authentication, SecurityConfig still checks if that authenticated user has permission for the specific endpoint. They work together:
JwtFilter says: "This user is John"
SecurityConfig says: "John is allowed to access /api/user/profile but NOT /api/admin/dashboard"
NOTE : We register request filters inside securityConfig but the order in which you add these filters or middlewares is different than nodeJs. In Nodejs the order in which you mention "app.use()" is order in which filters get applied, but Spring boot has 15+ built-in filters running, you insert yours at specific positions.
In the above example we put JwtFilter right BEFORE Spring's UsernamePasswordAuthenticationFilter, so we validate JWT before we authenticate user.
Spring boot internally maintains a filter chain which is created at the start of application. When you add@EnableWebSecurityto yourSecurityConfigclass, Spring Security automatically:
Creates the filter chain with all 15+ built-in filters
Orders them in a specific sequence
Registers them with your application
// Spring Security internal code (you don't write this)
publicclassSpringSecurityAutoConfiguration {
publicvoidbuildFilterChain() {
// Spring automatically creates and orders these filters:
The Builder Pattern is a design pattern where methods modify and return the same object, allowing you to chain method calls together in a fluent, readable sequence. Each method returns the sameHttpSecurityobject, allowing methods to be chained. This creates code that reads like a sentence describing the configuration.
After all methods are called and .build() executes, you get a SecurityFilterChain object that contains:
Request matcher — which URLs this chain applies to
Ordered filter list — all filters in correct sequence
@EnableWebSecurity is Spring Security's master switch. It's the annotation that transforms your regular Spring Boot application into a secured application with authentication and authorization capabilities. It tells Spring: "Enable all security features for this application."
Spring Security automatically builds a chain of 15+ filters that every request must pass through. It imports all the necessary Spring Security configuration classes. It makes theHttpSecuritybuilder available so you can customize security rules.
6] PasswordEncoder (The Scrambler)
This is a utility that ensures passwords are never stored in plain text.
Two operations:
encode(password) — scrambles password before saving to database
matches(rawPassword, encodedPassword) — checks if login password matches stored scrambled version
Why BCrypt?
Built-in salt to prevent rainbow table attacks
Adaptive algorithm (can be made slower over time)
Industry standard for password hashing
Why needed: If your database gets hacked, plain text passwords are catastrophic. With BCrypt, attackers only get scrambled strings that are computationally infeasible to reverse.
The 3 Are Main Components
Component
Why It's Main
Why Others Are Support
JwtService
Core JWT operations
Everything depends on it
JwtFilter
Connects JWT to Spring Security
Without it, JWT is useless
SecurityConfig
Defines all rules
Without it, no security policy
The other 3 (UserDetailsService, AuthenticationManager, PasswordEncoder) are Spring Security's native components — they'd exist even without JWT. The main 3 are what you add to make JWT work with Spring Security.
NOTE : The "other 3" are for the login process only. Once a user has a JWT token, you only need JwtService and JwtFilter. If you're using custom authentication logic, you don't need UserDetailsService, PasswordEncoder, or AuthenticationManager.
OncePerRequestFilter is an abstract base class provided by Spring that guarantees your filter executes exactly once per request, even if the request goes through multiple internal forwards, includes, or error pages. Every class that extendsOncePerRequestFilterMUST overridedoFilterInternal().
Custom filters are your own logic that you insert into Spring Security's filter chain. They allow you to intercept requests and responses at specific points in the request lifecycle.
Think of them as custom checkpoints in the security system — you decide what happens at each checkpoint.
Below are 2 steps to create a custom request filter :
1] Create a new Java class that extends OncePerRequestFilter and override doFilterInternal().
2] In your SecurityConfig class, use one of the registration methods to insert your filter into Spring's filter chain. Without registration, Spring doesn't know WHERE in the chain to place your filter
Lombok is a Java library that automatically generates boilerplate code at compile time using annotations. It saves you from writing repetitive code like getters, setters, constructors, toString, equals, hashCode, and builders.
Maven (pom.xml):
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Lombok is NOT specific to JPA. It's a general-purpose Java library that works with ANY Java class. JPA entities require many repetitive elements:
Useful : 1] Click 2] " Click " NOTE : In the "Reducer" function always have a 'default' switch case,else you'll get Undefined state error. Redux.JS Redux is an open-source state management javascript library. As the application grows, it becomes difficult to keep it organized and maintain data flow. Redux solves this problem by managing application’s state with a single global object called Store. Redux itself is a standalone library that can be used with any UI layer or framework, including React, Angular, Vue, Ember, and vanilla JS. Although Redux and React are commonly used together, they are independent of each other. NOTE : The data in react always flows from parent to child components,which makes react "Unidirectional" . Unlike react, Angular makes use of bi-directional binding in which the data flow takes place in both directions. What problem does Redux solve ? So, state is everywhere in ...
Useful : 1] Click 2] Click 3] React Roadmap React is an open source, JavaScript library for developing user interface (UI) in web application. React is developed and released by Facebook in 2013 . React has a component based architecture i.e everything is a component ,this let you break-down your application into small parts which can then be composed to make complex interfaces. In the past, when browsers were much less capable than today, and JavaScript performance was poor, every page was coming from a server. Every time you clicked something, a new request was made to the server and the browser subsequently loaded the new page. Today, popularized by modern frontend JavaScript frameworks like React, an app is usually built as a single page application: you only load the application code (HTML, CSS , JavaScript ) once, and when you interact with the application, what generally happens is that JavaScript intercepts the browser events and instead of making ...
Module Bundlers ( Useful :1] Click 2] Click ) Web browsers can only understand and execute JavaScript, HTML and CSS . However, developers often use other technologies and tools like React, Sass, TypeScript, and Tailwind to improve the development process, write more maintainable code, and add additional functionality to their applications. We need a way to combine all this JS & CSS code into a single optimized javascript file, this is achieved through module bundling. A module bundler is a tool that takes all the JavaScript files in a project and combines them into a single JS file (or a few files) that can be loaded by a browser. It usually starts with an entry point file, and from there it will start looking for "import" statements and then bundles up all of code needed for that entry file. The entry point is typically defined in the config file of the bundler. The entry point is the file where the bundler starts its traversal of the application's dependencies...
Comments
Post a Comment