Spring Security 6 with Spring Boot: A Complete Beginner to Advanced Guide
Spring Security 6 with Spring Boot: A Complete Beginner to Advanced Guide
π Premium PDF
Get the complete Spring Security 6 with Spring Boot PDF for offline learning and quick revision. Click the button below to unlock your free PDF.
Introduction
Get the complete Spring Security 6 with Spring Boot PDF for offline learning and quick revision. Click the button below to unlock your free PDF.
Imagine you've spent months building an amazing web application. The user interface looks beautiful, the APIs work perfectly, and the database is optimised. But one day, an unauthorised user gains access to your application and views confidential information.
This isn't a bug in your business logic—it's a security problem.
In today's digital world, security is no longer optional. Whether you're building a banking application, an e-commerce platform, a healthcare system, or a simple employee management portal, protecting user data is one of the most important responsibilities of a developer.
This is where Spring Security comes in.
Spring Security is the official security framework for the Spring ecosystem. It helps developers implement authentication, authorisation, session management, password encryption, CSRF protection, OAuth2 login, JWT authentication, and many other security features without building everything from scratch.
If you're new to Spring Security, the number of concepts—filters, authentication managers, security contexts, providers, JWTs, OAuth2, and more—can feel overwhelming. The good news is that these concepts become much easier once you understand how they work together.
In this guide, we'll build that understanding step by step. We'll start with the fundamentals, move through the internal architecture, and then build real applications using Spring Boot 3 and Spring Security 6.
By the end of this guide, you'll not only know how to configure Spring Security but also why each component exists and when to use it.
What You Will Learn
By following this guide, you'll learn how to:
- Secure Spring Boot applications using Spring Security 6
- Understand authentication and authorisation in depth
-
Configure Spring Security using the latest
SecurityFilterChain - Create custom login and logout functionality
- Store users in a database and authenticate them securely
- Encrypt passwords with BCrypt
- Build secure REST APIs using JWT
- Add Google and GitHub login using OAuth2
- Protect applications against CSRF attacks
- Configure CORS correctly
- Implement role-based access control
- Apply security best practices used in production
- Avoid common mistakes developers make when implementing security
Whether you're preparing for interviews, building personal projects, or developing enterprise applications, the knowledge you gain here will be directly applicable.
Prerequisites
Before starting, you should have a basic understanding of:
- Java 17 or later
- Spring Boot fundamentals
- Maven
- REST APIs
- Basic SQL
- JPA or Hibernate (recommended but not mandatory)
You don't need prior experience with Spring Security. Every concept will be introduced from the ground up.
Why Is Application Security Important?
Think about the applications you use every day:
- Gmail stores your emails.
- Amazon stores your orders and payment details.
- Online banking applications manage your money.
- Hospital systems contain sensitive patient records.
- Company portals store employee information and payroll data.
Now imagine if anyone on the internet could access that data without proper verification.
The consequences could include:
- Identity theft
- Financial fraud
- Data breaches
- Loss of customer trust
- Legal and regulatory penalties
- Damage to a company's reputation
Application security exists to prevent these problems. It ensures that users can access only the resources they're authorised to use and that sensitive information remains protected from attackers.
For example, in an Employee Management System:
- An employee should be able to view their own profile.
- A manager should be able to approve leave requests for their team.
- An administrator should be able to manage users and system settings.
- An anonymous visitor should not be able to access any of these features.
Without proper security, enforcing these rules consistently would be difficult and error-prone.
Why Spring Security?
You could write your own authentication and authorisation logic, but doing so would require implementing:
- Login validation
- Password hashing
- Session management
- Authorisation rules
- CSRF protection
- Security headers
- OAuth2 integration
- Remember-me functionality
- Logout handling
- Protection against common web attacks
Developing and maintaining all of these features correctly is a significant challenge.
Spring Security provides a well-tested framework that addresses these concerns and integrates seamlessly with Spring Boot.
Some of its key capabilities include:
- Authentication using usernames and passwords
- Role- and authority-based authorisation
- Password encryption with BCrypt
- Session and logout management
- CSRF protection
- CORS support
- OAuth2 login with providers such as Google and GitHub
- JWT-based authentication for REST APIs
- Method-level security
-
Integration with databases through
UserDetailsService
These features allow developers to focus on business logic while relying on a mature security framework for authentication and authorisation.
Authentication vs Authorisation in Spring Security
"How can we ensure that only the right people access the right resources?"
Imagine you have developed an Employee Management System for your company. The application contains sensitive information, including employee profiles, salaries, leave records, payroll data, and performance reviews. If anyone on the internet could access this information, it would lead to serious security and privacy issues.
To prevent this, every modern application follows two fundamental security processes:
- Authentication
- Authorization
These two concepts are the foundation of application security. Every secure application—whether it's Gmail, Amazon, Facebook, a banking system, or an enterprise application built with Spring Boot—relies on them.
Although developers often use these terms together, they have completely different responsibilities.
Authentication answers one question:
"Who are you?"
Authorisation answers another:
"What are you allowed to do?"
Think of authentication as verifying a person's identity and authorisation as deciding what that verified person is permitted to access.
Before an application decides whether you can open a page, update data, or delete a record, it must first verify your identity. Only after your identity has been confirmed does the application check your permissions.
This is why authentication always happens before authorisation.
Understanding Authentication
Authentication is the process of verifying the identity of a user, application, or system before granting access to protected resources.
In simple words, authentication confirms that the person trying to log in is genuinely who they claim to be.
Whenever you open an application and enter your username and password, you are participating in the authentication process.
But authentication is much more than simply comparing a username and password.
Modern applications support many different ways of verifying identity, including:
- Username and Password
- One-Time Password (OTP)
- Fingerprint Authentication
- Face Recognition
- Google Sign-In
- GitHub Login
- Microsoft Login
- Apple Sign-In
- Security Keys (FIDO2/WebAuthn)
- Multi-Factor Authentication (MFA)
Regardless of the method used, the goal remains the same:
Verify the user's identity before allowing access to protected resources.
A Real-World Example of Authentication
Imagine you work for a software company.
Every morning, you arrive at the office entrance. Before entering, the security guard asks for your employee ID card.
The guard carefully checks several things:
- Does this employee ID belong to the company?
- Is the ID genuine?
- Has the ID expired?
- Is the employee currently active?
If all these checks are successful, the security guard allows you to enter the building.
Notice something important.
The guard has not decided whether you can enter the HR department or the server room.
The guard has only confirmed your identity.
That entire verification process is called authentication.
The same principle applies in software applications.
Authentication in a Spring Boot Application
Suppose we have developed an Employee Management System using Spring Boot and Spring Security.
When an employee opens the login page, they enter:
Username: john Password: Password@123
After clicking the Login button, Spring Security begins the authentication process.
Although this happens in just a fraction of a second, several important steps take place behind the scenes.
Step 1: The Login Request
The browser sends the username and password to the Spring Boot application.
POST /login
The request reaches Spring Security before it reaches your controller.
This is one of the biggest advantages of Spring Security—it intercepts the request automatically and performs all the security checks for you.
Step 2: Extracting Credentials
Spring Security reads the submitted username and password from the HTTP request.
For example:
Username = john Password = Password@123
At this point, Spring Security does not know whether these credentials are valid.
It simply extracts them from the request.
Step 3: Finding the User
Next, Spring Security needs to determine whether a user named john actually exists.
Depending on your application, the user information might come from:
- Memory
- MySQL Database
- PostgreSQL
- Oracle Database
- LDAP
- Active Directory
- OAuth Provider
- JWT Token
Most enterprise applications retrieve user information from a database using a custom UserDetailsService.
Suppose the database contains the following record:
| Username | Password | Role |
|---|---|---|
| john | BCrypt Hash | ADMIN |
Notice that the password is not stored as plain text.
Instead, it is stored as an encrypted BCrypt hash.
This is an important security practice because storing plain-text passwords is extremely dangerous.
Step 4: Password Verification
Many beginners think Spring Security decrypts the stored password.
It doesn't.
Algorithms such as BCrypt are one-way hashing algorithms, which means the original password cannot be recovered.
Instead, Spring Security hashes the password entered by the user using the same algorithm and compares the resulting hash with the one stored in the database.
If both hashes match, the password is considered valid.
Otherwise, authentication fails.
Step 5: Creating the Authentication Object
Once the credentials are verified, Spring Security creates an Authentication object.
This object contains information about the currently logged-in user, such as:
- Username
- Password (credentials are typically cleared after successful authentication)
- Roles
- Authorities
- Authentication status
Spring Security stores this object in the SecurityContext.
From this point onward, any part of the application can determine who the current user is.
Step 6: Authentication Completed
At this stage, Spring Security has successfully answered one question:
"Who is the current user?"
However, it has not yet decided whether the user can access a specific resource.
That responsibility belongs to authorisation.
Spring Security Architecture
Introduction
Now let's answer one of the most common questions developers ask.
"What actually happens inside Spring Security when a user sends a request?"
For example, suppose a user opens a browser and visits:
http://localhost:8080/dashboard
The browser sends an HTTP request to your Spring Boot application.
At first glance, it might seem like the request goes directly to your controller.
However, that's not what happens.
Before the request reaches your controller, it passes through several security components. Each component performs a specific responsibility, such as checking whether the user is authenticated, verifying permissions, protecting against attacks, and managing the current user's security information.
Only after all these security checks are successfully completed does the request reach your business logic.
This complete flow is known as the Spring Security Architecture.
Understanding the Request Flow
Imagine an airport.
Before passengers board an aircraft, they don't go directly to the boarding gate. Instead, they must pass through several checkpoints.
Each checkpoint has a different responsibility.
- The first checkpoint verifies the passenger's ticket.
- The second checkpoint checks identity using a passport or ID.
- The security team scans baggage.
- Immigration verifies travel permissions.
- Finally, passengers are allowed to board the aircraft.
If a passenger fails any checkpoint, they are stopped immediately.
The same concept is followed in Spring Security.
Every HTTP request must pass through multiple security checkpoints before reaching the application.
HTTP Request │ ▼ Spring Security Filters │ Authentication Check │ Authorization Check │ Security Validation │ ▼ Spring Controller │ ▼ Business Logic │ ▼ HTTP Response
Instead of allowing every request directly into the application, Spring Security carefully examines each request to ensure it is safe.
Why Does Spring Security Use an Architecture?
Many beginners wonder why Spring Security contains so many components.
Why can't it simply check the username and password?
The answer is flexibility.
Different applications require different security mechanisms.
For example:
An online banking application may require:
- Username and Password
- OTP verification
- JWT authentication
- Role-based authorization
A social media application might allow:
- Google Login
- Facebook Login
- GitHub Login
An enterprise application may use:
- LDAP Authentication
- Active Directory
- Single Sign-On (SSO)
Instead of writing a separate framework for every authentication mechanism, Spring Security uses a modular architecture.
Each component performs one specific task.
This makes Spring Security:
- Flexible
- Extendable
- Easy to customise
- Easy to maintain
Step 1 – Browser Sends the Request
Everything starts when a user interacts with your application.
For example:
- Clicking the Login button
- Opening the Dashboard
- Viewing Employee Details
- Updating a Profile
- Calling a REST API
The browser sends an HTTP request to the Spring Boot application.
Example:
GET /dashboard HTTP/1.1 Host: localhost:8080
At this point, Spring Security has not yet decided whether the user is allowed to access this resource.
Step 2 – DispatcherServlet Receives the Request
Every Spring MVC application has a central servlet called the DispatcherServlet.
It acts as the front controller of the application.
Think of the DispatcherServlet as the receptionist in a company. Every visitor first meets the receptionist, who determines where they should go next.
Similarly, every incoming request first reaches the DispatcherServlet.
However, before the request is handed over to your controller, Spring Security intercepts it using a chain of servlet filters.
This is where the security process begins.
Step 3 – DelegatingFilterProxy
The first Spring Security component involved is the DelegatingFilterProxy.
Although it is registered as a standard servlet filter, it does not perform authentication or authorisation itself.
Instead, it acts as a bridge between the servlet container and the Spring Application Context.
Its primary job is simple:
- Receive the incoming request.
- Locate the Spring-managed security filter.
- Forward the request to that filter.
You can think of it as a receptionist who doesn't solve the problem but knows exactly which department should handle it.
Step 4 – FilterChainProxy
The request is then passed to the FilterChainProxy.
This is one of the core components of Spring Security.
Instead of executing security logic directly, the FilterChainProxy decides which Security Filter Chain should handle the current request.
For example, your application might have different security rules for:
-
/api/** -
/admin/** -
/public/**
The FilterChainProxy selects the appropriate filter chain based on the request URL.
This allows different parts of the application to have different security configurations.
Step 5 – Security Filter Chain
The Security Filter Chain is the heart of Spring Security.
Rather than relying on a single filter, Spring Security uses a chain of specialised filters. Each filter has one responsibility.
Examples include:
- Reading login credentials.
- Validating JWT tokens.
- Checking CSRF tokens.
- Processing logout requests.
- Verifying user permissions.
- Translating security exceptions into HTTP responses.
Each request moves through these filters one after another.
If a filter determines that the request should not continue—for example, because the user is not authenticated—it immediately stops the chain and returns an appropriate response such as 401 Unauthorised or 403 Forbidden.
If all filters complete successfully, the request proceeds to the controller.
Why Is This Architecture Powerful?
The filter-based architecture gives Spring Security several advantages:
- Each filter has a single responsibility, making the code easier to understand and maintain.
- Developers can add, remove, or replace filters without changing the rest of the framework.
- Different URL patterns can use different security configurations.
- New authentication mechanisms such as JWT or OAuth2 can be integrated by adding dedicated filters instead of rewriting the entire security system.
π Congratulations!
You have successfully completed the Spring Security 6 with Spring Boot guide.
Download the complete PDF for offline learning and quick revision.
Thank you for learning with AI Career Hub. Keep learning and keep growing! π
This modular design is one of the reasons Spring Security is trusted in enterprise applications.
Learning becomes easier when topics are connected. Browse the related articles below to continue your journey and discover more valuable concepts explained in a beginner-friendly way.
π Related Articles
Top 25 Java Interview Questions and Answers for Freshers (2026)
top-10-spring-boot-interview-questions-and-answers-2026
introduction-to-java-complete-beginners-guide
Complete Java Developer Roadmap Explained (2026)
Java OOP(Object Oriented Programming) Concepts
Continue your learning journey with more helpful guides and practical resources. Explore the related articles below to strengthen your knowledge and build your skills step by step.
https://aicareerinsights.blogspot.com/
Comments
Post a Comment