In Part 1, we understood Spring Security filters and how requests pass through the security filter chain.
In Part 2, we explored authentication using AuthenticationManager, AuthenticationProvider, DaoAuthenticationProvider, UserDetailsService, and BCrypt.
Now let's connect everything to a real-world REST API.
Imagine a user logs in successfully.
What happens next?
Should the user send their username and password with every request? Should the server remember that the user has logged in? Or should the server issue a token that the client sends with future requests?
These questions lead us to three important concepts:
- Session-based authentication
- Token-based authentication using JWT
- Single Sign-On (SSO)
We'll also walk through your SecurityConfig and JwtFilter code line by line, understand how JWT authentication works inside the Spring Security filter chain, and identify a few important improvements.
Table of contents
- Start with the problem: remembering a logged-in user
- Why applications use sessions
- What happens during session-based authentication
- Where sessions become difficult
- Move from sessions to tokens
- What is a token?
- What is JWT?
- Understand the three parts of a JWT
- JWT is signed, not encrypted
- How JWT authentication works
- Step 1: User logs in
- Step 2: Server creates a JWT
- Step 3: Client stores and sends the JWT
- Step 4: Server validates the JWT
- Step 5: Spring Security establishes authentication
- Understand SSO
- What problem does SSO solve?
- How SSO works at a high level
- OAuth 2.0 and OpenID Connect are not the same thing
- Connect JWT to your Spring Security filter chain
- Why add a custom JWT filter?
- Understand OncePerRequestFilter
- Understand addFilterBefore
- Walk through your JwtFilter
- Read the Authorization header
- Extract the token and username
- Load the user details
- Validate the token
- Create an authenticated Authentication object
- Continue the filter chain
- Review your SecurityConfig
- Disable CSRF: when is it appropriate?
- Configure stateless sessions
- Why formLogin and httpBasic need attention
- An important alternative: Spring Security OAuth2 Resource Server
- Which approach should I use?
- Common mistakes
- Quick recap
- Try it yourself
Start with the problem: remembering a logged-in user
Let's take a simple example.
You open an application and log in using:
Username: ram Password: r@123 The application verifies your credentials.
Great! You are logged in.
Now you click on another page:
GET /users/profile The server receives another request.
But here's the problem.
HTTP is a stateless protocol.
It does not automatically remember that you logged in while making the previous request.
From the server's perspective, the new request is just another HTTP request.
So how does the application know that the person requesting /users/profile is the same person who logged in earlier?
This is where sessions and tokens come into the picture.
Why applications use sessions
A session is a mechanism that allows the server to remember information about a client across multiple HTTP requests.
Think of visiting a hotel.
You check in at the reception and receive a room key.
You don't need to prove your identity again every time you enter your room. The key helps the hotel recognize that you have already checked in.
A session works in a similar way.
After successful login, the server creates a session and gives the client a session identifier.
The client sends that identifier with subsequent requests.
The server uses it to find the corresponding session and identify the logged-in user.
What happens during session-based authentication
Let's follow the process.
Step 1: User logs in
The client sends credentials:
POST /login Content-Type: application/x-www-form-urlencoded username=ram&password=r%40123 Step 2: Server verifies credentials
Spring Security authenticates the user using the configured authentication mechanism.
Step 3: Server creates a session
After successful authentication, the server can create an HTTP session.
It stores the security context containing the authenticated user's information in that session.
Step 4: Server sends a session cookie
The response can contain:
Set-Cookie: JSESSIONID=abc123; HttpOnly; Secure The browser stores this cookie.
Step 5: Client sends the cookie with future requests
When the browser requests another protected endpoint, it sends:
GET /users/profile Cookie: JSESSIONID=abc123 The server reads the session identifier, finds the session, and restores the user's authentication information.
The complete flow:
User Login | v Username + Password | v Server verifies credentials | v Authentication successful | v Create HTTP Session | v Store SecurityContext | v Send JSESSIONID cookie | v Browser stores cookie | v Future request includes JSESSIONID | v Server retrieves session | v User is recognized Notice something important.
The browser does not need to send the username and password again.
It sends the session identifier instead.
Where sessions become difficult
Session-based authentication works perfectly well for many applications.
But what happens when your application grows?
Imagine an application with three backend servers:
Load Balancer | +---------+---------+ | | | v v v Server A Server B Server C A user logs in, and Server A creates a session.
The session is stored in Server A's memory.
Now the next request reaches Server B.
What happens?
Server B may not know anything about the session created by Server A.
The application needs a solution.
Common approaches include:
1. Sticky sessions
Configure the load balancer to send a user's requests to the same server.
This can work, but it reduces flexibility and introduces dependency on the original server.
2. Shared session storage
Store sessions in a shared system such as Redis.
All application servers can retrieve session information from the same location.
This is a common solution and works well when session-based authentication is appropriate.
3. Token-based authentication
Instead of depending on a server-side session for every request, the server can issue a signed token that the client presents later.
This brings us to JWT.
One important clarification: sessions are not inherently bad or outdated. Shared session storage can scale very well. JWT is simply another authentication design with different trade-offs.
Move from sessions to tokens
What is a token?
A token is a piece of data that represents some information or permission.
In authentication, a token can be issued after successful login.
The client sends that token with future requests to prove that it has the required authentication information.
For example:
GET /users/profile Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... The server receives the token and verifies whether it is valid.
If it is valid, the application can establish the user's authentication.
A token is not automatically secure just because it is called a token.
Its format, signature, validation, storage, expiration, and transport all matter.
What is JWT?
JWT stands for JSON Web Token.
It is a compact token format used to transfer claims between parties.
A claim is simply a piece of information about an entity.
For example:
{ "sub": "ram", "role": "USER", "exp": 1790000000 } This payload contains information about a user and an expiration time.
JWT is commonly used for authentication and authorization, but remember:
JWT is a token format. It is not an authentication protocol by itself.
A JWT can be used as an access token, but OAuth 2.0 and OpenID Connect define broader authentication and authorization flows.
Understand the three parts of a JWT
A typical signed JWT contains three parts separated by dots.
HEADER.PAYLOAD.SIGNATURE Let's understand them.
1. Header
The header contains information about the token, such as the signing algorithm and token type.
Example:
{ "alg": "HS256", "typ": "JWT" } Here:
-
algrepresents the signing algorithm. -
typidentifies the token type.
2. Payload
The payload contains claims.
Example:
{ "sub": "ram", "role": "USER", "iat": 1790000000, "exp": 1790003600 } Some commonly used claims are:
-
sub: Subject, usually identifying the user. -
iat: Issued-at timestamp. -
exp: Expiration timestamp. -
iss: Issuer of the token. -
aud: Intended audience.
You can also include custom claims, such as roles or permissions.
3. Signature
The signature helps the receiver verify that the token was signed using the expected key and that its signed contents have not been modified.
For example, with an HMAC-based algorithm, the signing operation conceptually uses:
HMAC( secret, base64Url(header) + "." + base64Url(payload) ) The actual JWT specification defines the precise encoding and signing process.
The complete structure:
+----------------------------------+ | HEADER | | | | Algorithm: HS256 | | Type: JWT | +----------------------------------+ . +----------------------------------+ | PAYLOAD | | | | Subject: ram | | Role: USER | | Expiration: timestamp | +----------------------------------+ . +----------------------------------+ | SIGNATURE | | | | Verifies token integrity | +----------------------------------+ JWT is signed, not encrypted
This is one of the most important things to understand.
A normal signed JWT is not encrypted.
Its header and payload are Base64URL-encoded, which means anyone who gets the token can decode and read them.
For example, never put these values in a normal JWT payload:
- Passwords.
- Database credentials.
- API secrets.
- Private personal information.
The signature protects the integrity of the token. It does not hide the payload.
If you need confidentiality, use an appropriate encryption mechanism, such as an encrypted JWT (JWE), or avoid putting sensitive data in the token.
Also, don't confuse Base64URL encoding with encryption. Encoding is reversible without a secret key.
How JWT authentication works
Now let's follow a complete JWT authentication flow.
Imagine we have a Spring Boot backend and a frontend application.
The user wants to access:
GET /users/profile But the endpoint requires authentication.
Step 1: User logs in
The user sends their credentials to the backend.
POST /users/login Content-Type: application/json Request body:
{ "username": "ram", "password": "r@123" } The backend verifies these credentials using the authentication mechanism we discussed in Part 2.
Conceptually:
Login Controller | v AuthenticationManager | v DaoAuthenticationProvider | v UserDetailsService | v PasswordEncoder | v Authentication successful The user is now authenticated.
Step 2: Server creates a JWT
After successful authentication, the application creates a JWT.
For example:
{ "sub": "ram", "role": "USER", "iat": 1790000000, "exp": 1790003600 } The backend signs the token using a secret key or a private key, depending on the selected signing algorithm.
The server sends the token to the client.
Example response:
{ "token": "eyJhbGciOiJIUzI1NiJ9..." } The client now has a token that it can present with future requests.
Important: The JWT generation logic belongs to your application or an authorization server. AuthenticationManager authenticates credentials; it does not automatically generate a JWT.
Step 3: Client stores and sends the JWT
The client needs to store the token somewhere and send it when accessing protected endpoints.
A common request format is:
GET /users/profile Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... Why the word Bearer?
It indicates that the request is presenting a bearer token.
In simple terms, whoever possesses the token can attempt to use it.
This is why protecting the token is extremely important.
Token storage depends on your frontend architecture and threat model.
- Browser applications must carefully consider XSS and CSRF risks.
- An HttpOnly, Secure cookie can reduce JavaScript access to the token, but cookie-based authentication requires appropriate CSRF protection.
- Storing tokens in local storage exposes them to JavaScript running in the page, so an XSS vulnerability can expose the token.
There is no universally safe storage location for every application.
Step 4: Server validates the JWT
The backend receives the request:
GET /users/profile Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... It extracts the token and validates it.
The server should verify:
- The token's signature is valid.
- The token has not expired.
- The token is not being used before its valid-from time, if that claim is present.
- The issuer is trusted, when issuer validation is required.
- The audience is correct, when audience validation is required.
- Any additional application-specific requirements are satisfied.
Why do we need signature validation?
Imagine an attacker modifies the payload:
{ "sub": "ram", "role": "ADMIN" } The attacker changes the role from USER to ADMIN.
If the server simply decodes the payload and trusts it, the attacker could impersonate an administrator.
But the attacker cannot produce a valid signature without the required signing key.
The server verifies the signature before trusting the claims.
Never authenticate a user by simply decoding a JWT and reading its username.
Decoding and validation are two different operations.
Step 5: Spring Security establishes authentication
After successful token validation, Spring Security needs to represent the user as an authenticated principal.
It creates an authenticated Authentication object.
The authentication is then placed in the SecurityContextHolder.
Conceptually:
Incoming HTTP Request | v JWT Filter | v Extract Bearer Token | v Validate JWT | v Identify the user | v Create Authentication | v SecurityContextHolder | v Authorization checks | v Controller executes This is how a JWT becomes part of Spring Security's authentication system.
The token itself is not the same thing as Spring Security's Authentication object.
The token is the credential presented by the client. The Authentication object represents the result of authentication inside Spring Security.
Understand SSO
We have understood sessions and JWT.
Now let's look at another concept you mentioned: SSO.
What problem does SSO solve?
SSO stands for Single Sign-On.
Imagine working in an organization that provides these applications:
+----------------------+ | Company Portal | +----------------------+ +----------------------+ | Email App | +----------------------+ +----------------------+ | HR Application | +----------------------+ +----------------------+ | Project Tool | +----------------------+ Without SSO, you might need separate login credentials for each application.
That means:
- Login to the company portal.
- Login again to email.
- Login again to the HR application.
- Login again to the project tool.
That's inconvenient.
SSO solves this problem by centralizing the authentication experience.
You authenticate with a trusted identity provider, and participating applications can rely on that provider's authentication process.
For example, you may sign in once using your organization account and then access multiple applications without entering your credentials again.
How SSO works at a high level
Let's understand the flow.
Suppose you open an application called HR App.
Step 1: Open the application
You visit:
https://hr.example.com The application does not have an authenticated user session.
Step 2: Redirect to the identity provider
The application redirects you to a centralized identity provider.
For example:
https://login.example.com Step 3: Authenticate with the identity provider
You enter your company credentials.
The identity provider verifies your identity.
Step 4: Identity provider returns an authentication result
Depending on the protocol and flow, the identity provider returns an authorization response or token to the application.
Step 5: Application establishes its own security context
The application validates the response and establishes the user's authenticated state.
Later, when you open another participating application, it can redirect you to the same identity provider.
Since you already have an active identity-provider session, you may not need to enter your credentials again.
The simplified flow:
User | v HR App | v Redirect to Identity Provider | v User authenticates once | v Identity Provider verifies | v Authentication response | v HR App | v User authenticated | v Open another company app | v Same Identity Provider | v Existing login may be reused Notice that SSO is not the same thing as JWT.
SSO is an authentication experience and architecture.
JWT is a token format that may be used as part of that architecture.
OAuth 2.0 and OpenID Connect are not the same thing
You will often hear OAuth 2.0 and OpenID Connect when learning SSO.
They are related, but they solve different problems.
OAuth 2.0
OAuth 2.0 is an authorization framework.
It allows an application to obtain limited access to resources on behalf of a user or another client.
For example, an application may receive permission to access a user's calendar without receiving the user's password.
OpenID Connect (OIDC)
OpenID Connect is an identity layer built on top of OAuth 2.0.
It adds standardized authentication and identity information.
It commonly uses an ID token to communicate information about the authenticated user.
A simple way to remember:
OAuth 2.0 | v Authorization | v What is this application allowed to access? OpenID Connect | v Authentication + Identity | v Who is the user? Spring Security provides support for OAuth2 Resource Server, OAuth2 Client, and OAuth2 Login.
For SSO using an external identity provider, OAuth2 Login with OpenID Connect is a common choice.
Connect JWT to your Spring Security filter chain
Now comes the practical part.
You shared this configuration:
.addFilterBefore( jwtFilter, UsernamePasswordAuthenticationFilter.class ) And you also shared a class called JwtFilter.
Let's understand why you need this filter and how it works.
Why add a custom JWT filter?
Remember the Spring Security filter chain from Part 1?
Incoming requests pass through security filters before reaching the DispatcherServlet.
A JWT filter is responsible for checking whether the incoming request contains a bearer token and, if so, authenticating that token.
For example:
GET /users/profile Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... Your custom filter can:
- Read the Authorization header.
- Extract the token.
- Identify the username.
- Load the user's details.
- Validate the token.
- Create an authenticated
Authenticationobject. - Store it in the security context.
- Continue the filter chain.
Why do we need to do this before the controller executes?
Because authorization checks need to know who the current user is.
If the request reaches the authorization stage without an authenticated user, Spring Security can reject access to protected endpoints.
Understand OncePerRequestFilter
Your filter extends:
OncePerRequestFilter This is a Spring Web filter base class.
It provides a convenient way to implement filter logic that should be executed once per request dispatch, subject to its dispatch and configuration rules.
Instead of implementing the entire servlet Filter lifecycle yourself, you override:
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain ) throws ServletException, IOException { // Your filter logic } Spring calls this method when the filter is invoked.
Why is this useful?
Because you can focus on the actual work:
- Read the request.
- Inspect the token.
- Authenticate the user.
- Continue processing.
You don't need to write the same filter lifecycle boilerplate repeatedly.
Understand addFilterBefore
Your configuration contains:
.addFilterBefore( jwtFilter, UsernamePasswordAuthenticationFilter.class ) What does this mean?
It tells Spring Security to place your custom filter before UsernamePasswordAuthenticationFilter in the security filter chain.
Conceptually:
Incoming Request | v +-----------------------------+ | Your JwtFilter | +-----------------------------+ | v +-----------------------------+ | UsernamePasswordAuthenticationFilter | +-----------------------------+ | v +-----------------------------+ | Other Security Filters | +-----------------------------+ | v +-----------------------------+ | Authorization | +-----------------------------+ | v DispatcherServlet The actual chain contains additional filters, and their ordering is managed by Spring Security.
The important point is that your JWT filter gets an opportunity to establish authentication before the later authorization checks.
Why choose UsernamePasswordAuthenticationFilter as the reference point?
It is a familiar authentication filter in Spring Security's username/password form-login flow.
Placing a custom JWT filter before it is a common approach in custom JWT implementations.
However, when using Spring Security's built-in OAuth2 Resource Server support, you normally don't need to write this custom filter yourself.
Walk through your JwtFilter
Let's revisit your original code.
@Component public class JwtFilter extends OncePerRequestFilter { @Autowired private JWTService jwtService; @Autowired private ApplicationContext context; @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain ) throws ServletException, IOException { String authHeader = request.getHeader("Authorization"); String token = null; String username = null; if (authHeader != null && authHeader.startsWith("Bearer ")) { token = authHeader.substring(7); username = jwtService.extractUsername(token); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = context.getBean(MyUserDetailsService.class) .loadUserByUsername(username); if (jwtService.validateToken(token, userDetails)) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); authenticationToken.setDetails( new WebAuthenticationDetailsSource() .buildDetails(request) ); SecurityContextHolder.getContext() .setAuthentication(authenticationToken); } } } filterChain.doFilter(request, response); } } Let's break it into smaller pieces.
Read the Authorization header
String authHeader = request.getHeader("Authorization"); Every HTTP request can contain headers.
Your client sends:
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... This line reads the Authorization header.
Then:
String token = null; String username = null; We initialize two variables.
-
tokenwill hold the JWT. -
usernamewill hold the username extracted from the token.
Next:
if (authHeader != null && authHeader.startsWith("Bearer ")) { We check two things:
- The Authorization header exists.
- The header starts with
Bearer.
Why check Bearer?
Because the Authorization header can support different authentication schemes.
For example:
Authorization: Basic dXNlcjpwYXNz This is HTTP Basic authentication.
But our custom filter expects a bearer token.
Extract the token and username
Now look at:
token = authHeader.substring(7); Why 7?
Because the string:
Bearer contains seven characters.
The actual JWT starts after those seven characters.
Example:
Bearer eyJhbGciOiJIUzI1NiJ9... | v JWT starts here So substring(7) extracts the token.
Next:
username = jwtService.extractUsername(token); Here, you call your custom JWTService.
Its responsibility is to extract the username from the token.
For example, your token may contain:
{ "sub": "ram", "role": "USER" } The service extracts the subject:
ram One important security detail:
Extracting a claim is not the same as validating a token.
Your extractUsername() method may be able to decode an unverified token. Therefore, do not trust the extracted username or use it for authorization until the token's signature and required claims have been validated.
Your code does not establish authentication at this point, which is good, but the validation step must be robust.
Load the user details
Now look at this condition:
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { We check two things.
First: Username exists
username != null If we couldn't extract a username, we shouldn't continue with user lookup.
Second: No authentication already exists
SecurityContextHolder.getContext().getAuthentication() == null Why?
Because another authentication mechanism may already have established authentication for this request.
We don't want to blindly overwrite an existing authentication.
Now comes the user lookup:
UserDetails userDetails = context.getBean(MyUserDetailsService.class) .loadUserByUsername(username); Let's break it down.
context.getBean(MyUserDetailsService.class) You are asking Spring's ApplicationContext for the MyUserDetailsService bean.
Then:
.loadUserByUsername(username); You load the user details from your user storage.
For example:
Username extracted from JWT: ram | v MyUserDetailsService | v Database lookup | v UserDetails object Why load the user again?
Your application may need the latest account status and authorities from the database.
For example, an administrator may have disabled the account after the token was issued.
Loading the user gives your application an opportunity to check current account information.
There is a trade-off: database lookup on every request adds work. Some designs rely on validated token claims instead, but then revocation and permission changes become harder to handle.
Validate the token
Now we reach:
if (jwtService.validateToken(token, userDetails)) { This is one of the most important lines in your JWT filter.
The token must be validated before it is trusted.
Your JWTService should verify the signature and relevant claims, including expiration.
Depending on your application, it should also validate issuer, audience, and other required claims.
For example:
Token: Subject: ram Expiration: valid Signature: valid UserDetails: Username: ram Enabled: true Result: Authentication can be established If the token is expired, incorrectly signed, malformed, or otherwise invalid, authentication must not be established.
One thing I cannot verify from the code you shared is whether your JWTService.validateToken() actually checks all these conditions. We would need to inspect that implementation.
Create an authenticated Authentication object
Now suppose token validation succeeds.
Your code creates:
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); Remember this from Part 2?
We discussed the two co...