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
- Move from sessions to tokens
- How JWT authentication works
- Understand SSO
- Connect JWT to your Spring Security filter chain
- Review your SecurityConfig
- 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 constructors of UsernamePasswordAuthenticationToken.
This constructor accepts:
principal,
credentials,
authorities
Here:
Principal
userDetails
The authenticated user's details.
Credentials
null
We don't need to retain the original password as credentials.
Authorities
userDetails.getAuthorities()
The user's granted authorities.
For example:
ROLE_USER
ROLE_ADMIN
Because we are using the constructor with authorities, the resulting token is marked as authenticated.
This is why we must only create it after successfully validating the JWT.
Next:
authenticationToken.setDetails(
new WebAuthenticationDetailsSource()
.buildDetails(request)
);
What does this do?
It attaches request-related details to the authentication object.
For example, the details can include the remote IP address and session identifier when available.
These details are not the user's identity or permissions. They are additional request metadata.
Continue the filter chain
Finally:
SecurityContextHolder.getContext()
.setAuthentication(authenticationToken);
This stores the authenticated user in the current security context.
Now Spring Security can identify the user during the remaining processing of the request.
And then:
filterChain.doFilter(request, response);
This is extremely important.
It tells the servlet filter chain to continue processing the request.
What happens if you forget this line?
The request may never reach the remaining filters or the DispatcherServlet.
Your controller might never execute.
The complete flow of your filter:
Incoming Request
|
v
Read Authorization Header
|
v
Does it contain Bearer token?
|
+------ No ------> Continue Filter Chain
|
Yes
|
v
Extract JWT
|
v
Extract Username
|
v
Is username available and
authentication not already set?
|
+------ No ------> Continue Filter Chain
|
Yes
|
v
Load UserDetails
|
v
Validate JWT
|
+------ Invalid --> Do not authenticate
|
Valid
|
v
Create authenticated Authentication
|
v
Store in SecurityContextHolder
|
v
Continue Filter Chain
Review your SecurityConfig
Let's now look at the important parts of your configuration.
Your code:
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http,
JWTService jWTService
) throws Exception {
return http
.csrf(customizer -> customizer.disable())
.authorizeHttpRequests(request -> request
.requestMatchers(
"/users/register",
"/users/login"
)
.permitAll()
.anyRequest()
.authenticated()
)
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
.addFilterBefore(
jwtFilter,
UsernamePasswordAuthenticationFilter.class
)
.build();
}
Let's understand the important decisions.
Disable CSRF: when is it appropriate?
Your configuration contains:
.csrf(customizer -> customizer.disable())
What is CSRF?
CSRF stands for Cross-Site Request Forgery.
It is an attack where an attacker tricks a user's browser into sending an unwanted request to a website where the user is already authenticated.
Imagine:
- You log in to your banking website.
- Your browser stores an authentication cookie.
- You visit a malicious website.
- That website tricks your browser into sending a request to the banking website.
- Your browser automatically includes the banking cookie.
- The banking application may process the unwanted request if it lacks proper CSRF protection.
Why does the browser automatically send the cookie?
Because cookies are associated with the target website and are automatically included according to cookie rules.
This is why cookie-based authentication needs appropriate CSRF protection.
Now consider a different design.
Your frontend explicitly sends a JWT in this header:
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
A malicious website generally cannot cause the browser to automatically attach your application's bearer token from local storage to an arbitrary cross-site request.
This changes the CSRF threat model.
For a carefully designed API that uses only explicitly supplied bearer tokens in the Authorization header, disabling CSRF may be appropriate.
But don't blindly disable CSRF just because you use JWT.
If your JWT is stored in a cookie and the browser automatically sends it, CSRF protection may still be necessary.
Also, if your application uses form login or other cookie-based authentication, disabling CSRF can introduce risk.
Configure stateless sessions
Your code:
.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
Let's understand SessionCreationPolicy.
Spring Security provides different session creation policies.
Some commonly used values are:
-
ALWAYS: Always create an HTTP session. -
IF_REQUIRED: Create a session when required. -
NEVER: Do not create a session, but use an existing one if available. -
STATELESS: Do not create or use an HTTP session to obtain theSecurityContext.
For a stateless JWT API, we commonly use:
SessionCreationPolicy.STATELESS
Why?
Because we want every request to carry the credentials needed for authentication.
The application validates the token and establishes authentication for that request.
It does not depend on an HTTP session to remember the user's authentication across requests.
The flow becomes:
Request 1
|
v
JWT validation
|
v
Authentication established
|
v
Request processed
Request 2
|
v
JWT validation again
|
v
Authentication established again
|
v
Request processed
Each request is authenticated independently.
Important: Stateless does not mean your application cannot use a database, Redis, or other storage. It means the security context is not persisted in an HTTP session as the mechanism for remembering authentication.
Why formLogin and httpBasic need attention
Your configuration also contains:
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
These enable two additional authentication mechanisms.
formLogin
Enables Spring Security's form-based login support.
httpBasic
Enables HTTP Basic authentication, where credentials are sent using the Basic Authorization scheme.
But your application is also using a custom JWT filter and STATELESS session management.
Is that wrong?
Not necessarily. Spring Security can support multiple authentication mechanisms.
However, you should decide which authentication mechanisms your application actually needs.
If your application is a REST API where users log in using JSON and authenticate future requests using JWT, you generally don't need the default form-login mechanism.
You may also not need HTTP Basic.
A cleaner JWT-oriented configuration could look like this:
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http
) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/users/register",
"/users/login"
).permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session
.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
.addFilterBefore(
jwtFilter,
UsernamePasswordAuthenticationFilter.class
)
.build();
}
This is only a simplified configuration for an API that uses an explicitly supplied bearer token and does not rely on cookie-based authentication.
In production, also configure suitable authentication entry points, exception handling, CORS where needed, and robust invalid-token handling.
One more important detail:
permitAll() means that authorization does not require authentication for the matched endpoint.
It does not automatically skip your custom JWT filter.
Your filter still runs for those requests. In your current implementation, requests without a bearer token simply continue, which allows registration and login requests to reach their controllers.
However, if an invalid bearer token is supplied to a public endpoint, your filter should handle that situation deliberately.
An important alternative: Spring Security OAuth2 Resource Server
There is something important I want you to know before building more custom JWT logic.
You do not always need to write your own JWT filter.
Spring Security already provides JWT bearer-token authentication through its OAuth2 Resource Server support.
It provides components such as:
BearerTokenAuthenticationFilterJwtAuthenticationProviderJwtDecoderJwtAuthenticationConverter
The framework can handle bearer-token extraction, JWT decoding, signature validation, and authentication establishment.
A simplified configuration can look like this:
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http
) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/users/register",
"/users/login"
).permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session
.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
)
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
)
.build();
}
You also need the appropriate Resource Server and JOSE dependencies and a JwtDecoder configuration, such as a trusted issuer or public key.
For example, when using a trusted JWT issuer:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com/issuer
The issuer must be a real, trusted authorization server configured for your application.
With this setup, Spring Security can validate JWTs using its built-in infrastructure.
The simplified internal flow looks like this:
Incoming Request
|
v
BearerTokenAuthenticationFilter
|
v
Extract Bearer Token
|
v
AuthenticationManager
|
v
JwtAuthenticationProvider
|
v
JwtDecoder
|
v
Verify Signature and Claims
|
v
JwtAuthenticationToken
|
v
SecurityContextHolder
This is similar to the custom flow we implemented, but Spring Security manages the JWT authentication infrastructure.
When should you choose this?
- Use Resource Server support when you want Spring Security to validate bearer JWTs.
- Use a custom filter when you have a specific authentication requirement that the built-in support does not address.
- Avoid writing your own cryptographic token validation when the framework already provides a suitable implementation.
For most standard JWT-protected APIs, I would start by evaluating Resource Server support before implementing a custom filter.
Which approach should I use?
Let's compare the three concepts we covered.
Session-based authentication
Choose it when:
- You are building a traditional server-rendered web application.
- You want server-managed login state.
- You want straightforward session invalidation.
- Your application can use a suitable shared session store when scaling across servers.
JWT-based authentication
Choose it when:
- You are building APIs accessed by separate clients.
- You need bearer-token authentication.
- Multiple services need to validate tokens.
- You have a clear strategy for expiration, revocation, and token storage.
SSO
Choose it when:
- Multiple applications need a centralized login experience.
- You want an identity provider to manage authentication.
- You are building an organization-wide authentication system.
- You need a standard protocol such as OpenID Connect.
Remember:
- Session is a way to maintain login state.
- JWT is a token format.
- SSO is a centralized authentication experience.
- OAuth 2.0 is an authorization framework.
- OpenID Connect adds an identity layer to OAuth 2.0.
These concepts can work together. For example, an SSO identity provider may issue JWT access tokens to multiple applications.
Common mistakes
Assuming JWT is encrypted: A normal signed JWT has a readable Base64URL-encoded payload. Never put passwords, secrets, or sensitive information inside it. Use encryption when confidentiality is required.
Trusting a decoded JWT without validating it: Decoding only reveals the claims. Always verify the signature and required claims before trusting the token.
Assuming JWT automatically solves scalability: JWT can reduce dependence on server-side session storage, but applications still need to handle token expiration, revocation, signing-key rotation, and permission changes.
Disabling CSRF just because the application uses JWT: If authentication credentials are stored in cookies that browsers automatically send, CSRF protection may still be required. Understand how your client sends credentials before disabling protection.
Forgetting
filterChain.doFilter(): A filter must continue the chain when it has finished processing the request. Otherwise, later filters and the DispatcherServlet may never execute.Mixing authentication mechanisms without a reason: Enabling form login, HTTP Basic, and custom JWT authentication together can make the security configuration harder to understand. Enable only the mechanisms your application actually needs.
Quick recap
- HTTP is stateless, so applications need a way to recognize authenticated users across requests.
- Session-based authentication stores login state on the server.
- Browsers commonly send a session identifier using a cookie such as
JSESSIONID. - Shared session storage can help session-based applications scale across multiple servers.
- JWT stands for JSON Web Token.
- A signed JWT has three parts: header, payload, and signature.
- A normal signed JWT is not encrypted.
- The server must validate the JWT before trusting its claims.
- A bearer token is commonly sent using the
Authorizationheader. -
SecurityContextHolderprovides access to the current security context. - SSO allows multiple applications to rely on a centralized authentication experience.
- OAuth 2.0 is an authorization framework, while OpenID Connect adds identity and authentication.
-
OncePerRequestFilteris useful for implementing custom servlet filters. -
addFilterBefore()controls where a custom filter is placed in the Spring Security filter chain. -
SessionCreationPolicy.STATELESSprevents Spring Security from using an HTTP session to persist authentication. - Spring Security OAuth2 Resource Server can handle standard JWT bearer-token authentication without a custom JWT filter.
Try it yourself
Now that you understand the complete flow, try implementing it.
Practice 1: Understand session authentication
Create a basic Spring Boot application with form login.
Log in and inspect the browser's cookies.
Find the JSESSIONID cookie and observe what happens when you access another protected endpoint.
Practice 2: Generate a JWT
Create a login endpoint.
After successful authentication, generate a JWT containing:
- Username as the subject.
- Issued-at time.
- Expiration time.
- User role.
Return the token in the response.
Practice 3: Implement JWT authentication
Create a custom OncePerRequestFilter.
Extract the bearer token, validate it, load the user, and establish authentication using SecurityContextHolder.
Test the following situations:
- No token.
- Valid token.
- Expired token.
- Invalid signature.
- Unknown username.
- Disabled user.
Observe how your application handles each request.
Practice 4: Compare custom JWT filters with Resource Server
Try configuring Spring Security's OAuth2 Resource Server support.
Compare its authentication flow with your custom JwtFilter.
Understand which responsibilities Spring Security handles automatically.
Bonus challenge
Build a small application with these endpoints:
POST /users/register
POST /users/login
GET /users/profile
GET /users/admin
Requirements:
- Store passwords using BCrypt.
- Authenticate login credentials using
AuthenticationManager. - Generate a JWT after successful login.
- Protect the profile endpoint.
- Allow only administrators to access
/users/admin. - Reject expired or invalid tokens.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)