spring-security
Table of Contents
What⌗
Spring Security is a powerful framework used to secure Java-based applications. It provides comprehensive support for authentication (Verifying the identity of a user), authorization (Determining what resources a user can access) for java application.
Why⌗
It helps in protecting user data, It also protects developer’s logic.
How to add spring security in your spring boot project⌗
STEP 1 {Configuration}⌗
Add the latest spring-boot-starter-security
dependency in your pom.xml file.
You can check the latest version from here.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>3.4.0</version>
</dependency>
If you run your spring boot app now after adding this dependency and try to hit your endpoint you may observe a login page whose password is given in your console/log window and by default username would be user
.
STEP 2.0 {Customization}⌗
Adding Custom user and password manually for single user.
Go to.properties
file and add these lines:
#Spring Security Configurations
spring.security.user.name = yourUserName
spring.security.user.password = yourPassword
For more properties like this visit here.
STEP 2.1 {Customization}⌗
Adding custom user and password using java configuration class.
// In-Memory {No Database} User Detail Management Using Springboot.
@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService(){
// InMemory User Creation User1 User2
UserDetails user1 = User
.withDefaultPasswordEncoder()
.username("apple")
.password("apple123#")
.roles("ADMIN")
.build();
UserDetails user2 = User
.withDefaultPasswordEncoder()
.username("bannana")
.password("bannana123#")
.roles("GUEST")
.build();
// InMemoryUserDetailManager is a child class of UserDetailsService Interface.
// So we can return it's Object directly. InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(user1,user2);
return inMemoryUserDetailsManager;
}
}
- To load user we use #UserDetailService interface
Locates the user based on the username
. - To use this interface we need to create an object of its implementation class which is
InMemoryUserDetailsManager
class. - In InMemoryUserDetailManager constructor we can pass users created using UserDetails.
- Run your app again and hit your endpoints.
Internal Flow Of Spring Security⌗
Diagram⌗
Login Process in Short⌗
- Client enter username and password and send.
- The request first get’s intercepted by spring security filters.
- A authentication object is created containing username and password.
- The authentication object is passed to authentication manager.
- Authentication manager finds all the supported authentication provider for the authentication object.
- Logic is processed in authentication provider.
- Finally in the end authentication provider uses User Detail Service to fetch the data from database using authentication object username and password.
- If username and password match in the database then the authentication flag is turned to true and returned to Security Context Holder.
- The response is sent to user.
- Done.
Above Process in a story format⌗
When a user tries to log in, they start by entering their username and password in the login form and sending the request.
As soon as the request reaches the server, Spring Security steps in. The request is first intercepted by a series of security filters, which are part of Spring Security’s filter chain.
These filters take the credentials and create an Authentication
object that holds the username and password. This object doesn’t confirm anything yet — it just represents the user’s attempt to log in.
Next, the Authentication
object is passed to the Authentication Manager, whose job is to figure out how to verify the credentials. It does this by checking all the available Authentication Providers that know how to handle this type of login.
One of the providers picks up the request and starts the actual authentication process. To verify the user’s identity, it uses the UserDetailsService — a component responsible for loading user data from the database.
The UserDetailsService looks up the user by the provided username and compares the submitted password with the stored (usually encoded) one. If they match, the user is considered authenticated.
At this point, the Authentication object’s flag is set to authenticated = true, and this verified object is stored in the SecurityContextHolder — Spring’s way of keeping track of who’s logged in during the session.
Finally, a success response is sent back to the client, confirming the user is logged in — and the process is complete.
Login Process in Depth⌗
We all remember this sign in page when we just started learning spring security. Although this page style is basic but when we click on
sign in
the working behind it is not the basic one which we encounter.
Lets dive deep into it’s working:
- When user hit the login form by providing username and password, The Spring security calls AttemptAuthentication() method to validate the credentials.
In Short this method do all these functionality:
- Extract Credentials: Fetches the
username
andpassword
from the HTTP request. - Create Token: Constructs a
UsernamePasswordAuthenticationToken
using the credentials and set the Authentication = false. - Authenticate: Passes the token object to the Authenticate() method inside the
ProviderManager
which implementAuthenticationManager
for validation against the user database or service. - Return Authentication: If valid, returns an authenticated
Authentication
object; if not, throws an exception.
- Authenticate(token Object) Method have username, password and authentication status{true/false} from the token object.
- The Authenticate method finds the providers for the token. {Authentication Provider–> It is responsible for performing authentication logic. Providers validate authentication requests (tokens) and decide whether the provided credentials are valid, ultimately returning an authenticated user or rejecting the authentication attempt.}
- The appropriate provider after implementing logic calls the
retriveUser(username, UsernamePasswordToken token)
, this method fetch the user from Database/InMemoryUser/CustomUser. - The fetched data will go through some more additional check and post additional checks and then returned back as a response.
Above Process in story format by AI⌗
🔐 The Story Behind the Spring Security Login Page⌗
We all remember that simple white login form Spring Security gives us when we first start learning.
It may look plain and straightforward, but behind that innocent-looking Sign In button lies a powerful and detailed security process.
Let’s walk through what really happens when you hit “Sign In”.
🚪 Step 1: Knocking on the Door – User Submits Credentials⌗
A user enters their username and password, then clicks the login button.
At this moment, Spring Security triggers a method called attemptAuthentication()
.
This method is like a doorman checking the credentials. Here’s what it quietly does behind the scenes:
-
Extracts Credentials
It grabs the username and password from the HTTP request. -
Creates a Token
It creates aUsernamePasswordAuthenticationToken
— think of this as a little ID card with the username, password, and a flag that says “not authenticated yet”. -
Starts Authentication
This token is passed to theauthenticate()
method insideProviderManager
, which is Spring’s authentication boss.
🧠 Step 2: Who Can Verify This Token?⌗
Now that Spring has this authentication token, it asks:
“Which of my Authentication Providers can handle this?”
It scans through all its available Authentication Providers to find one that can work with the token.
🧩 Think of an Authentication Provider as the brain that knows how to validate the login details — it could check a database, an in-memory list, a remote service, etc.
📇 Step 3: Retrieving User Details⌗
Once the right provider is found, it says:
“Let me look up this user…”
It calls the method retrieveUser(username, token)
, which does the job of:
-
Looking up the user from your database, or
-
Fetching from in-memory users, or
-
Calling a custom user service, depending on your setup.
✅ Step 4: Final Checks and Response⌗
With the user details in hand, Spring Security runs a few additional checks — like verifying the password, checking if the account is locked or expired, etc.
If everything is valid:
-
The authentication token’s flag is set to true (authenticated).
-
The user is now considered logged in.
-
Spring stores this in the Security Context, so it knows who you are for future requests.
If anything is invalid:
- Spring throws an authentication exception and sends you back to the login page with an error.
🏁 And That’s It!⌗
From a simple “Sign In” button click to a series of secure checks and authentications —
Spring Security does a lot under the hood to keep your app safe.
So the next time you see that plain login form, you’ll know there’s a whole team of security guards working in the background to protect your app. 🛡️
Filters Chains⌗
🔐 Login Request Flow in Spring Security⌗
1. DisableEncodeUrlFilter⌗
📛 Prevents session IDs from being added to URLs (old-school fallback).
2. WebAsyncManagerIntegrationFilter⌗
🔄 If you’re using async calls, this keeps your security info safe across threads.
3. SecurityContextHolderFilter⌗
🧠 Sets up the SecurityContext
— stores details about the logged-in user.
4. HeaderWriterFilter⌗
🛡️ Adds security headers like X-Frame-Options, Strict-Transport-Security, etc.
5. CsrfFilter⌗
🧾 If you’re submitting a form (POST), this checks if the CSRF token is valid.
6. LogoutFilter⌗
🚪 If the URL is /logout
, this clears session and logs out the user.
7. UsernamePasswordAuthenticationFilter⌗
🔐 If you’re submitting login credentials (/login
), this filter handles authentication.
8. DefaultLoginPageGeneratingFilter⌗
📄 If no custom login page is defined, this auto-generates a login form.
9. DefaultLogoutPageGeneratingFilter⌗
📄 Shows a logout success page if no custom one is given.
10. BasicAuthenticationFilter⌗
🔑 If using HTTP Basic Auth (like Authorization: Basic ...
), this authenticates the user.
11. RequestCacheAwareFilter⌗
💾 Remembers which page you wanted to access before login, so it can send you back there after login.
12. SecurityContextHolderAwareRequestFilter⌗
🧩 Adds helper methods to your request object like isUserInRole()
.
13. AnonymousAuthenticationFilter⌗
👤 If no one is logged in, this sets an “anonymous” user so nothing breaks.
14. ExceptionTranslationFilter⌗
🚨 Catches errors like access denied or not logged in and handles redirects or 403 errors.
15. AuthorizationFilter⌗
🔓 Final check: Is the user allowed to access this URL? If yes → allow, else → deny.
Internals of Spring Security⌗
Important Classes⌗
- SpringBootWebSecurityConfiguration
-> This class is the default configuration class of spring security.
-> This class have method{defaultSecurityFilterChain} to authorize every request.
-> It applies when no custom
SecurityFilterChain
bean is defined. -> Used for basic form based login. - HttpSecurity -> It allows configuring web based security for specific http requests. ->By default it will be applied to all requests, but can be restricted using requestMatcher(RequestMatcher) or other similar methods.
Important Methods⌗
- authorizeHttpRequests -> It’s a child of HttpSecurity class. -> It is used to define authorization rules -> eg: which HTTP requests require authentication and what roles/authorities are needed to access them.
Authentication and Authorization⌗
- Authentication is about verifying who you are.
- Authorization determines what you can do once you are Authenticated.
Authority and Role inside Authorization⌗
Authority⌗
- Authority represents a single permission or privilege a user has within the application.
- Spring security uses GrantedAuthority objects to determine if a user can perform a specific action.
Role⌗
- GrantedAuthority that groups related permissions together.
- It represents a broader user designation like “USER”, “ADMIN”, “EDITOR”.
- By default spring security have a “ROLE_” prefix attached (eg, “ROLE_ADMIN”)