Spring Security Interview Preparation
A. Spring Security Fundamentals Interview Tip: These are the foundation questions. Interviewers often ask follow-up questions from these topics, so understand the flow rather than memorizing definitions. Springβ¦
A. Spring Security Fundamentals
Interview Tip: These are the foundation questions. Interviewers often ask follow-up questions from these topics, so understand the flow rather than memorizing definitions.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Spring Security is a powerful authentication and authorization framework for Java and Spring applications. It helps secure REST APIs and web applications by protecting resources from unauthorized access.
It provides built-in support for:
- Authentication (Who are you?)
- Authorization (What can you access?)
- Password encryption
- JWT Authentication
- OAuth2
- CSRF Protection
- Session Management
- CORS Support
- Protection against common security attacks
It integrates seamlessly with Spring Boot.
Real-world Example
Suppose you have an e-commerce application.
- Customer can view products.
- Admin can add/delete products.
- Only logged-in users can place orders.
Spring Security ensures that users can access only the APIs they are permitted to use.
Example
GET /products β Public
POST /login β Public
POST /orders β Authenticated User
DELETE /products/10 β Admin Only
Interview One-Liner: Spring Security is a framework that provides authentication, authorization, and protection against common web security attacks.
Without security, anyone can access our APIs, steal data, modify information, or perform unauthorized actions.
Spring Security helps protect the application by:
- Verifying user identity (Authentication)
- Restricting access (Authorization)
- Encrypting passwords
- Protecting against attacks like CSRF and Session Hijacking
- Managing user sessions
- Supporting secure authentication mechanisms like JWT and OAuth2
Example
Without Security:
DELETE /users/5
Anyone can delete a user.
With Security:
DELETE /users/5
Only Admin users are allowed.
Benefits
- Secure APIs
- Role-based access
- Password encryption
- JWT support
- Easy integration with Spring Boot
- Highly customizable
Interview One-Liner: We use Spring Security to protect our application by authenticating users and authorizing access to resources.
Spring Security works using a chain of filters called the Security Filter Chain.
Every incoming HTTP request first passes through these filters before reaching the controller.
The filters perform tasks like:
- Authentication
- Authorization
- JWT Validation
- Session Validation
- Exception Handling
If all security checks pass, the request reaches the controller.
Otherwise, Spring Security returns 401 Unauthorized or 403 Forbidden.
Internal Flow
Client
β
HTTP Request
β
Security Filter Chain
β
Authentication Filter
β
Authorization Filter
β
Controller
β
Business Logic
β
Response
JWT Example
1. User sends JWT token.
2. JWT Filter extracts the token.
3. Token is validated.
4. User details are loaded.
5. Authentication object is created.
6. SecurityContext stores the authenticated user.
7. Request reaches the controller.
Interview One-Liner: Spring Security intercepts every request using the Security Filter Chain and performs authentication and authorization before allowing access.
These are two different security concepts.
| Authentication | Authorization |
|---|---|
| Verifies identity | Verifies permissions |
| “Who are you?” | “What can you do?” |
| Happens first | Happens after authentication |
| Uses username/password, JWT, OAuth | Uses roles and permissions |
Example
User logs in:
Username:
john
Password:
******
Authentication checks if the credentials are correct.
After login:
DELETE /users/10
Authorization checks whether John has permission to delete users.
Real-world Example
Bank ATM
Authentication
- Insert ATM card
- Enter PIN
Authorization
- Withdraw money
- Check balance
- Transfer money
Interview One-Liner: Authentication verifies user identity, while authorization determines what resources the authenticated user can access.
Spring Security follows a layered architecture where each component has a specific responsibility.
Main components include:
- Security Filter Chain
- Authentication Manager
- Authentication Provider
- UserDetailsService
- PasswordEncoder
- SecurityContext
- Authorization Manager
Architecture Flow
Client
β
Security Filter Chain
β
AuthenticationManager
β
AuthenticationProvider
β
UserDetailsService
β
Database
Component Responsibilities
Security Filter Chain
- Intercepts every request.
AuthenticationManager
- Coordinates the authentication process.
AuthenticationProvider
- Validates user credentials.
UserDetailsService
- Loads user information from the database.
PasswordEncoder
- Compares encrypted passwords.
SecurityContext
- Stores authenticated user details for the current request.
Interview One-Liner: Spring Security uses components like Security Filter Chain, AuthenticationManager, AuthenticationProvider, UserDetailsService, and SecurityContext to authenticate and authorize requests.
The Security Filter Chain is a collection of security filters that process every incoming HTTP request.
Instead of directly calling the controller, the request passes through multiple filters.
Each filter performs a specific security task.
Common Filters
- CORS Filter
- CSRF Filter
- JWT Authentication Filter
- UsernamePasswordAuthenticationFilter
- Authorization Filter
- ExceptionTranslationFilter
Flow
Request
β
Filter 1
β
Filter 2
β
JWT Filter
β
Authorization Filter
β
Controller
Why is it important?
It allows Spring Security to:
- Validate tokens
- Authenticate users
- Check permissions
- Handle security exceptions
Interview One-Liner: The Security Filter Chain is a sequence of filters that intercept every request and apply security checks before the request reaches the controller.
Every request follows a fixed sequence before reaching the application.
Flow
Client
β
HTTP Request
β
Security Filter Chain
β
Authentication
β
Authorization
β
Controller
β
Service
β
Database
β
Response
JWT Request Flow
1. Client sends JWT token in the Authorization header.
2. JWT filter extracts the token.
3. Token is validated.
4. User details are loaded.
5. Authentication object is stored in SecurityContext.
6. Authorization checks required roles or authorities.
7. Controller processes the request.
8. Response is returned.
Possible Responses
- 200 OK β Request is successful.
- 401 Unauthorized β User is not authenticated or token is invalid.
- 403 Forbidden β User is authenticated but does not have permission.
Interview One-Liner: Every request passes through the Security Filter Chain, where authentication and authorization are performed before the controller is invoked.
SecurityContext stores the authentication information of the currently logged-in user.
SecurityContextHolder is a utility class used to access the SecurityContext from anywhere in the application.
After successful authentication, Spring Security stores the Authentication object inside the SecurityContext.
Flow
Login Successful
β
Authentication Object
β
SecurityContext
β
SecurityContextHolder
β
Available throughout the request
Example
Authentication auth = SecurityContextHolder
.getContext
.getAuthentication;
String username = auth.getName;
Real-world Use
You can get the current logged-in user in your service layer without passing the username in every method.
Interview One-Liner: SecurityContext stores the current user’s authentication details, and SecurityContextHolder provides access to that context during the request.
These are key parts of the Authentication object.
Principal
Represents the authenticated user.
Examples:
- Username
- UserDetails object
- Custom user object
Credentials
Represents the user’s secret information.
Examples:
- Password
- JWT token (during authentication)
After successful authentication, credentials are often cleared for security reasons.
GrantedAuthority
Represents the permissions assigned to the user.
Examples:
ROLE_ADMIN
ROLE_USER
READ_PRODUCT
WRITE_PRODUCT
DELETE_ORDER
Spring Security uses these authorities during authorization.
Example
Principal:
john
Credentials:
********
Authorities:
ROLE_ADMIN
READ_PRODUCT
DELETE_PRODUCT
Interview One-Liner: Principal identifies the user, Credentials hold the secret used for authentication, and GrantedAuthority represents the permissions assigned to the user.
Both are used for authorization, but they have different purposes.
- Role is a high-level classification of a user.
- Authority is a specific permission or privilege.
A role usually contains one or more authorities.
Example
ROLE_ADMIN
Authorities:
READ_USER
CREATE_USER
UPDATE_USER
DELETE_USER
Here, an Admin role can perform multiple operations because it has several authorities.
Comparison
| Role | Authority |
|---|---|
| High-level user category | Specific permission |
| Example: ROLE_ADMIN | Example: READ_PRODUCT |
| Usually prefixed with ROLE_ | No prefix required |
| Can contain multiple authorities | Represents a single permission |
In Spring Security
.hasRole("ADMIN")
Spring automatically looks for:
ROLE_ADMIN
.hasAuthority("READ_PRODUCT")
Checks for the exact authority:
READ_PRODUCT
When to Use
- Use Roles for broad access control (Admin, Manager, User).
- Use Authorities for fine-grained permissions (Read, Write, Delete, Approve).
Interview One-Liner: A role is a broad user category, while an authority is a specific permission. In Spring Security, roles are typically prefixed with ROLE_, and each role can have multiple authorities.
β Interview Revision (1-Minute Recap)
- Spring Security secures Spring applications through authentication and authorization.
- Authentication answers *Who are you?*; Authorization answers *What can you access?*
- Every request passes through the Security Filter Chain before reaching the controller.
- AuthenticationManager coordinates authentication, AuthenticationProvider validates credentials, and UserDetailsService loads user details.
- SecurityContext stores the authenticated user’s information, while SecurityContextHolder provides access to it during the request.
- The Authentication object contains Principal (user), Credentials (secret), and GrantedAuthorities (permissions).
- Roles (e.g., ROLE_ADMIN) represent broad user categories, whereas Authorities (e.g., READ_PRODUCT) represent specific permissions.
B. Authentication
Interview Tip: Authentication is one of the most frequently asked Spring Security topics. Interviewers often ask the authentication flow after discussing JWT or Spring Security architecture.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Authentication is the process of verifying the identity of a user.
It answers the question:
“Who are you?”
The application checks whether the user is genuine by verifying credentials such as username/password, OTP, JWT token, OAuth token, etc.
If the credentials are valid, the user is authenticated. Otherwise, access is denied.
Example
Suppose a user tries to log in:
Username: prakash
Password: password123
Spring Security verifies these credentials from the database.
If they match:
- User is authenticated.
- Authentication object is created.
- User details are stored in the SecurityContext.
If they don’t match:
- Login fails.
- Spring Security returns 401 Unauthorized.
Real-world Example
ATM Machine
- Insert ATM Card
- Enter PIN
- Bank verifies PIN
If correct β You are authenticated.
Interview One-Liner: Authentication is the process of verifying a user’s identity before allowing access to an application.
This is the most common authentication mechanism.
The user enters a username and password. Spring Security validates them against stored user data.
If the credentials are correct:
- User is authenticated.
- Authentication object is created.
- User can access protected APIs.
Flow
User Login
β
Username & Password
β
AuthenticationManager
β
AuthenticationProvider
β
UserDetailsService
β
Database
β
PasswordEncoder
β
Authentication Success
Production Example
POST /login
{
"username":"john",
"password":"password123"
}
Spring Security validates the credentials and returns a JWT or creates a session depending on the application’s configuration.
Interview One-Liner: Username & Password Authentication validates the user’s credentials against stored user information before granting access.
InMemoryUserDetailsManager stores user information in application memory instead of a database.
It is mainly used for:
- Learning
- Testing
- Small applications
- Proof of Concept (POC)
When the application restarts, all users are lost because they are not stored permanently.
Example
@Bean
public UserDetailsService userDetailsService {
UserDetails user = User.builder
.username("admin")
.password(passwordEncoder.encode("admin123"))
.roles("ADMIN")
.build;
return new InMemoryUserDetailsManager(user);
}
Advantages
- Very easy to configure
- No database required
- Good for testing
Limitations
- Not suitable for production
- Data is not persistent
- Difficult to manage many users
Interview One-Liner: InMemoryUserDetailsManager stores users in memory and is mainly used for testing or small applications.
JDBC Authentication stores user credentials in a relational database.
Spring Security uses JDBC queries to fetch user information and authorities from database tables.
Unlike InMemoryUserDetailsManager, user data remains available after application restart.
Flow
Login Request
β
AuthenticationManager
β
JDBC Authentication
β
MySQL/PostgreSQL
β
User Details
Advantages
- Persistent user storage
- Suitable for production
- Easy user management
Limitations
- Fixed table structure by default
- Limited flexibility
Nowadays, many projects use Custom UserDetailsService with Spring Data JPA instead of built-in JDBC authentication.
Interview One-Liner: JDBC Authentication retrieves user details from a relational database using JDBC queries.
UserDetailsService is an interface used by Spring Security to load user information during authentication.
In real projects, we usually create our own implementation that fetches user details from the database using JPA or another persistence layer.
The interface contains one method:
UserDetails loadUserByUsername(String username)
If the user exists, it returns a UserDetails object.
If not, it throws UsernameNotFoundException.
Example
@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Autowired
private UserRepository repository;
@Override
public UserDetails loadUserByUsername(String username) {
User user = repository.findByUsername(username)
.orElseThrow( ->
new UsernameNotFoundException("User not found"));
return new CustomUserDetails(user);
}
}
Why do we need it?
- Fetch users from database
- Load roles and authorities
- Support custom user tables
- Integrate with JPA
Interview One-Liner: Custom UserDetailsService loads user information from the database and is the most common approach in production applications.
UserDetails is a Spring Security interface that represents an authenticated user.
It contains information required during authentication and authorization.
Typical information includes:
- Username
- Password
- Roles
- Authorities
- Account status
Important Methods
getUsername
getPassword
getAuthorities
isAccountNonExpired
isAccountNonLocked
isCredentialsNonExpired
isEnabled
Production Usage
In real applications, we usually create a custom class implementing UserDetails and map our database entity to it.
Interview One-Liner: UserDetails represents the authenticated user and provides username, password, authorities, and account status information.
Passwords should never be stored in plain text.
PasswordEncoder is a Spring Security interface used to:
- Encrypt passwords before storing them.
- Compare the login password with the stored encrypted password.
It provides methods like:
encode
matches
Example
Stored Password
$2a$10$6Kz9...
Login Password
admin123
Spring Security compares them using:
passwordEncoder.matches(rawPassword, encodedPassword)
Interview One-Liner: PasswordEncoder securely hashes passwords and verifies them during authentication.
BCryptPasswordEncoder is the most commonly used PasswordEncoder implementation in Spring Security.
It hashes passwords using the BCrypt algorithm.
The same password generates different hashes because BCrypt automatically adds a random salt.
Example
PasswordEncoder encoder = new BCryptPasswordEncoder;
String encoded = encoder.encode("admin123");
Possible Output
$2a$10$rG4s7K....
Advantages
- Strong hashing algorithm
- Automatic salting
- Resistant to rainbow table attacks
- Recommended for production
Interview One-Liner: BCryptPasswordEncoder securely hashes passwords with a random salt and is the recommended encoder for production.
DelegatingPasswordEncoder supports multiple password encoding algorithms.
It identifies the algorithm using a prefix stored with the password.
Example:
{bcrypt}$2a$10$....
or
{noop}password123
This allows applications to support old and new password formats during migration.
Why is it useful?
Suppose an old application stored passwords using SHA-256.
The new application uses BCrypt.
DelegatingPasswordEncoder can authenticate users using both formats until all passwords are migrated.
Interview One-Liner: DelegatingPasswordEncoder supports multiple password encoders and enables smooth migration between encoding algorithms.
AuthenticationManager is the central component responsible for authenticating users.
It receives an Authentication object and delegates the authentication request to one or more AuthenticationProviders.
If authentication succeeds, it returns a fully authenticated Authentication object.
If authentication fails, it throws an exception.
Flow
Login Request
β
AuthenticationManager
β
AuthenticationProvider
β
Authentication Result
Interview One-Liner: AuthenticationManager coordinates the authentication process by delegating authentication requests to AuthenticationProvider.
AuthenticationProvider performs the actual authentication logic.
It validates the user’s credentials.
Spring Security supports different providers for different authentication mechanisms, such as:
- Username & Password
- LDAP
- OAuth2
- JWT (custom implementation)
Responsibilities
- Validate credentials
- Load user details
- Verify password
- Return authenticated user
Interview One-Liner: AuthenticationProvider performs the actual authentication by validating user credentials and returning an authenticated user.
DaoAuthenticationProvider is the default AuthenticationProvider used for username/password authentication.
It works together with:
- UserDetailsService
- PasswordEncoder
Steps performed:
1. Calls UserDetailsService.
2. Loads user details.
3. Uses PasswordEncoder to compare passwords.
4. Returns an authenticated Authentication object if successful.
Flow
AuthenticationManager
β
DaoAuthenticationProvider
β
UserDetailsService
β
Database
β
PasswordEncoder
β
Authentication Success
Interview One-Liner: DaoAuthenticationProvider authenticates username/password users by using UserDetailsService to load user data and PasswordEncoder to verify passwords.
Authentication in Spring Security follows a well-defined sequence.
Step-by-Step Flow
Client
β
Login Request
β
UsernamePasswordAuthenticationFilter
β
AuthenticationManager
β
DaoAuthenticationProvider
β
UserDetailsService
β
Database
β
PasswordEncoder
β
Password Match?
β
Yes
β
Create Authentication Object
β
Store in SecurityContext
β
Return Success
Detailed Explanation
Step 1: User submits username and password.
Step 2: UsernamePasswordAuthenticationFilter captures the login request.
Step 3: It creates an unauthenticated UsernamePasswordAuthenticationToken.
Step 4: The token is passed to AuthenticationManager.
Step 5: AuthenticationManager delegates to DaoAuthenticationProvider.
Step 6: DaoAuthenticationProvider calls UserDetailsService to load user information.
Step 7: PasswordEncoder compares the entered password with the stored hashed password.
Step 8: If the password matches:
- An authenticated Authentication object is created.
- It is stored in the SecurityContext.
Step 9: The user is successfully authenticated. Depending on the application, Spring may create an HTTP session or return a JWT token.
If any step fails, Spring Security returns 401 Unauthorized.
β Interview Revision (1-Minute Recap)
- Authentication verifies a user’s identity.
- Username & Password Authentication is the most common authentication mechanism.
- InMemoryUserDetailsManager stores users in memory and is mainly for testing.
- JDBC Authentication loads users directly from a relational database.
- Custom UserDetailsService is the preferred production approach to load users using JPA.
- UserDetails represents the authenticated user.
- PasswordEncoder hashes and verifies passwords.
- BCryptPasswordEncoder is the recommended password hashing algorithm.
- DelegatingPasswordEncoder supports multiple encoding algorithms for easier migration.
- AuthenticationManager coordinates authentication.
- AuthenticationProvider performs the actual credential validation.
- DaoAuthenticationProvider uses UserDetailsService and PasswordEncoder for username/password authentication.
- Authentication Flow: Login Request β UsernamePasswordAuthenticationFilter β AuthenticationManager β DaoAuthenticationProvider β UserDetailsService β PasswordEncoder β SecurityContext β Success (Session/JWT) or 401 Unauthorized.
C. Authorization
Interview Tip: Authentication verifies who the user is, while Authorization determines what the user is allowed to do. Interviewers often ask these questions together.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Authorization is the process of determining whether an authenticated user has permission to access a particular resource or perform a specific action.
It answers the question:
“What are you allowed to do?”
Authorization happens after successful authentication.
Example
Suppose two users log in:
User 1 β ROLE_USER
User 2 β ROLE_ADMIN
API:
DELETE /users/10
- User β β Access Denied
- Admin β β Access Granted
Real-world Example
Airport
- Authentication β Passport verification
- Authorization β Whether you can enter the Business Lounge
Interview One-Liner: Authorization determines whether an authenticated user has permission to access a resource.
URL-based authorization secures APIs based on their URL patterns.
It is configured using HttpSecurity inside the SecurityFilterChain.
Example
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest.authenticated
);
How it works
Request
β
URL Pattern Match
β
Role Check
β
Allow / Deny
When to Use
- Secure REST APIs
- Public and private endpoints
- Different access for different URL patterns
Interview One-Liner: URL-based authorization secures endpoints by applying access rules based on URL patterns.
Method-level security protects individual methods instead of entire URLs.
Spring Security checks permissions before executing the method.
It provides more fine-grained security than URL-based authorization.
Example
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
}
Only Admin users can execute this method.
Advantages
- Fine-grained security
- Independent of URL
- Useful in service layer
Interview One-Liner: Method-level security secures individual methods using annotations like @PreAuthorize and @Secured.
@PreAuthorize checks authorization before a method executes.
If the user does not have permission, the method is never executed.
Example
@PreAuthorize("hasRole('ADMIN')")
public void deleteProduct {
}
Only users with the Admin role can execute the method.
More Examples
@PreAuthorize("hasAuthority('READ_PRODUCT')")
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
Interview One-Liner: @PreAuthorize checks permissions before method execution using Spring Expression Language (SpEL).
@PostAuthorize performs authorization after the method has executed.
It is useful when the authorization decision depends on the returned object.
Example
@PostAuthorize("returnObject.username == authentication.name")
public User getUser(Long id) {
}
The method executes first.
Spring then checks whether the returned user’s username matches the logged-in user.
When to Use
- Ownership checks
- Resource-level authorization
- Access based on returned data
Interview One-Liner: @PostAuthorize checks authorization after method execution, usually based on the returned object.
@Secured is an annotation used to restrict method access based on roles.
Unlike @PreAuthorize, it supports only role checks.
Example
@Secured("ROLE_ADMIN")
public void deleteUser {
}
Limitation
Cannot use complex expressions like:
hasAuthority('READ_PRODUCT')
or
authentication.name == #username
Interview One-Liner: @Secured restricts method access based only on roles and is less flexible than @PreAuthorize.
@RolesAllowed is a standard Java (JSR-250) annotation used for role-based authorization.
It behaves similarly to @Secured.
Example
@RolesAllowed("ADMIN")
public void createUser {
}
Difference
- @RolesAllowed is a Java standard annotation.
- @Secured is Spring-specific.
Interview One-Liner: @RolesAllowed is a standard Java annotation for role-based method security.
Both are used for authorization, but they work differently.
| hasRole | hasAuthority |
|---|---|
| Checks roles | Checks specific permissions |
| Automatically adds ROLE_ prefix | No prefix added |
| Used for broad access | Used for fine-grained access |
Example
.hasRole("ADMIN")
Spring internally checks:
ROLE_ADMIN
.hasAuthority("READ_PRODUCT")
Spring checks exactly:
READ_PRODUCT
When to Use
- hasRole β Admin, User, Manager
- hasAuthority β Read, Write, Delete, Approve
Interview One-Liner: hasRole checks roles (with the ROLE_ prefix), while hasAuthority checks exact permissions.
Role hierarchy allows one role to automatically inherit the permissions of another role.
Example
ROLE_ADMIN
β
ROLE_MANAGER
β
ROLE_USER
If Admin inherits Manager and User:
- Admin can perform all Manager operations.
- Admin can perform all User operations.
Benefits
- Reduces duplicate role assignments.
- Easier permission management.
- Cleaner security configuration.
Interview One-Liner: Role hierarchy allows higher roles to inherit the permissions of lower roles.
β Interview Revision (Authorization)
- Authorization decides what a user can access.
- URL-based authorization secures endpoints using URL patterns.
- Method-level security protects individual methods.
- @PreAuthorize checks before method execution.
- @PostAuthorize checks after method execution.
- @Secured supports only role checks.
- @RolesAllowed is the Java standard alternative.
- hasRole checks roles; hasAuthority checks specific permissions.
- Role hierarchy allows higher roles to inherit lower-role permissions.
Spring Security Interview Questions & Answers
D. Spring Security Configuration
Interview Tip: Since Spring Security 6, WebSecurityConfigurerAdapter has been removed. Most interviews now focus on SecurityFilterChain and HttpSecurity.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
SecurityFilterChain is the central configuration component in Spring Security 6.
It defines how incoming HTTP requests should be secured.
Instead of extending WebSecurityConfigurerAdapter, we now define a SecurityFilterChain bean.
Example
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.authorizeHttpRequests(auth -> auth
.anyRequest.authenticated);
return http.build;
}
Responsibilities
- Configure authentication
- Configure authorization
- Add custom filters
- Configure session management
- Configure CORS and CSRF
Interview One-Liner: SecurityFilterChain is the main Spring Security 6 configuration bean that defines how requests are secured.
HttpSecurity is a configuration builder used to customize Spring Security.
It allows us to configure:
- Authentication
- Authorization
- CSRF
- CORS
- Session Management
- Custom Filters
- Exception Handling
Example
http
.csrf(csrf -> csrf.disable)
.authorizeHttpRequests(auth -> auth
.anyRequest.authenticated);
Interview One-Liner: HttpSecurity is a fluent API used to configure Spring Security behavior.
authorizeHttpRequests is used to define authorization rules for HTTP requests.
It replaces the older authorizeRequests method introduced in earlier Spring Security versions.
Example
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest.authenticated);
Interview One-Liner: authorizeHttpRequests configures authorization rules for incoming HTTP requests.
requestMatchers specifies which URLs the security rule should apply to.
Example
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/public/**").permitAll
Interview One-Liner: requestMatchers selects the URL patterns to which security rules are applied.
permitAll allows anyone to access an endpoint without authentication.
Example
.requestMatchers("/login").permitAll
Common public endpoints:
- Login
- Register
- Swagger UI
- Health Check
Interview One-Liner: permitAll allows public access without requiring authentication.
authenticated requires the user to be logged in.
It does not check rolesβonly that the user is authenticated.
Example
.anyRequest.authenticated
Interview One-Liner: authenticated allows access only to authenticated users, regardless of their role.
denyAll blocks access to everyone, including authenticated users.
Example
.requestMatchers("/internal/**").denyAll
When to Use
- Disable endpoints
- Block deprecated APIs
- Temporary maintenance
Interview One-Liner: denyAll denies access to all users.
anonymous allows access only to users who are not logged in.
Authenticated users cannot access the endpoint.
Example
.requestMatchers("/login").anonymous
If a logged-in user accesses /login, access is denied or redirected.
Interview One-Liner: anonymous allows only unauthenticated users to access an endpoint.
securityMatcher specifies which requests a particular SecurityFilterChain should handle.
It is mainly used when configuring multiple filter chains.
Example
http.securityMatcher("/api/**");
Only requests starting with /api/ use this filter chain.
Interview One-Liner: securityMatcher restricts a SecurityFilterChain to specific request patterns.
Spring Security allows multiple SecurityFilterChain beans.
Each chain secures different types of requests.
Example
/api/** β JWT Authentication
/admin/** β Form Login
/public/** β No Authentication
Each filter chain has its own configuration.
Benefits
- Separate security rules
- Cleaner configuration
- Different authentication mechanisms
Interview One-Liner: Multiple SecurityFilterChain beans allow different security configurations for different request groups.
WebSecurityCustomizer is used to completely ignore specific requests from Spring Security.
Ignored requests do not pass through the Security Filter Chain.
It is commonly used for static resources.
Example
@Bean
public WebSecurityCustomizer webSecurityCustomizer {
return web -> web.ignoring
.requestMatchers("/css/**", "/js/**", "/images/**");
}
Difference from permitAll
| permitAll | WebSecurityCustomizer |
|---|---|
| Passes through security filters | Completely bypasses security filters |
| Security features still apply | No security processing at all |
Interview One-Liner: WebSecurityCustomizer excludes specific requests from Spring Security entirely and is mainly used for static resources.
β Interview Revision (Configuration)
- SecurityFilterChain is the main security configuration bean in Spring Security 6.
- HttpSecurity configures authentication, authorization, CSRF, CORS, sessions, and filters.
- authorizeHttpRequests defines authorization rules.
- requestMatchers selects URL patterns.
- permitAll allows public access.
- authenticated requires login.
- denyAll blocks everyone.
- anonymous allows only unauthenticated users.
- securityMatcher applies a filter chain to specific request patterns.
- Multiple SecurityFilterChain beans support different security configurations (e.g., JWT APIs and form login).
- WebSecurityCustomizer bypasses Spring Security completely for selected requests, typically static resources.
E. JWT Authentication
Interview Tip: JWT is one of the most frequently asked Spring Security topics. Be prepared to explain the complete JWT flow from login to API access.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
JWT (JSON Web Token) is a compact and secure token format used to authenticate users in stateless applications.
After a successful login, the server generates a JWT and sends it to the client. The client includes this token in every subsequent request.
Instead of storing user sessions on the server, Spring Security validates the JWT for each request.
Example
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Advantages
- Stateless authentication
- No server-side session storage
- Scalable for microservices
- Fast authentication
- Easy integration with REST APIs
Interview One-Liner: JWT is a stateless authentication mechanism where the server issues a signed token that the client sends with every request.
A JWT consists of three parts separated by dots.
Header.Payload.Signature
Example:
xxxxx.yyyyy.zzzzz
Structure
Header
β
Payload
β
Signature
Interview One-Liner: A JWT contains three parts: Header, Payload, and Signature.
Header
Contains metadata about the token.
Example:
{
"alg": "HS256",
"typ": "JWT"
}
Payload
Contains user information (claims).
Example:
{
"username": "john",
"role": "ADMIN",
"exp": 1750000000
}
Note: Never store sensitive information like passwords in the payload because it is Base64 encoded, not encrypted.
Signature
Used to verify that the token has not been modified.
Created using:
Header + Payload + Secret Key
If the payload changes, the signature becomes invalid.
Interview One-Liner: The Header stores metadata, the Payload stores claims, and the Signature ensures token integrity.
JWT authentication follows this sequence.
Client
β
Login Request
β
Spring Security
β
AuthenticationManager
β
UserDetailsService
β
Database
β
Authentication Success
β
Generate JWT
β
Return Token
β
Client Stores JWT
β
Authorization: Bearer <JWT>
β
JWT Filter
β
Validate Token
β
SecurityContext
β
Controller
Step-by-Step
1. User logs in.
2. Spring Security authenticates the user.
3. Server generates a JWT.
4. Client stores the JWT.
5. Client sends the JWT in every request.
6. JWT filter validates the token.
7. Authentication is stored in the SecurityContext.
8. Request reaches the controller.
Interview One-Liner: After login, the server generates a JWT. Every request carries the token, which Spring Security validates before allowing access.
| JWT Authentication | Session Authentication |
|---|---|
| Stateless | Stateful |
| No session stored | Session stored on server |
| Better for REST APIs | Better for traditional web apps |
| Scales easily | Harder to scale |
| Token sent in every request | Session ID sent in cookie |
Interview One-Liner: JWT is stateless and ideal for REST APIs, whereas Session Authentication stores user sessions on the server.
In stateless authentication, the server does not store any user session.
Each request contains all the information required for authentication, usually in the JWT.
Every request is authenticated independently.
Interview One-Liner: Stateless authentication means the server does not store user sessions; each request is authenticated using the JWT.
After successful authentication:
1. User logs in.
2. Credentials are validated.
3. Claims (username, roles, expiry) are prepared.
4. Token is signed using a secret key or private key.
5. JWT is returned to the client.
Common Claims
- Username
- User ID
- Roles
- Issued Time (iat)
- Expiration Time (exp)
Interview One-Liner: JWT is generated after successful authentication by adding user claims and signing them with a secret key.
For every incoming request, Spring Security checks:
- Signature is valid.
- Token is not expired.
- User exists.
- Token is not tampered with.
If valid, an authenticated Authentication object is created and stored in the SecurityContext.
Interview One-Liner: JWT validation verifies the signature, expiration, and token integrity before authenticating the user.
JWT contains an exp (expiration) claim.
When the token expires:
- Validation fails.
- Spring Security returns 401 Unauthorized.
- The client should obtain a new access token using a refresh token or log in again.
Interview One-Liner: Spring Security checks the exp claim and rejects expired tokens with a 401 response.
A Refresh Token is a long-lived token used to generate a new Access Token without requiring the user to log in again.
It is typically stored more securely than the Access Token.
Flow
Login
β
Access Token (15 min)
Refresh Token (7 days)
β
Access Token Expires
β
Refresh Token
β
Generate New Access Token
Interview One-Liner: A Refresh Token is used to obtain a new Access Token after the old one expires without asking the user to log in again.
| Access Token | Refresh Token |
|---|---|
| Short-lived | Long-lived |
| Used for API calls | Used to obtain new access tokens |
| Sent with every request | Used only when the access token expires |
| Higher exposure | Stored more securely |
Interview One-Liner: Access Tokens authenticate API requests, while Refresh Tokens generate new Access Tokens after expiry.
A JWT Filter intercepts every incoming request, extracts the JWT, validates it, and authenticates the user.
It runs before the request reaches the controller.
Responsibilities
- Read Authorization header.
- Extract JWT.
- Validate token.
- Load user details.
- Store authentication in SecurityContext.
Interview One-Liner: A JWT Filter validates the JWT on every request and authenticates the user before the controller is invoked.
OncePerRequestFilter is a Spring class that guarantees a filter executes only once for each HTTP request.
JWT filters typically extend this class.
Why Use It?
Without it, the filter may execute multiple times during a single request.
Example
public class JwtAuthenticationFilter
extends OncePerRequestFilter {
}
Interview One-Liner: OncePerRequestFilter ensures the JWT filter executes only once for each request.
A Custom Authentication Filter is a filter created by developers to implement custom authentication logic.
Common use cases:
- JWT validation
- API Key authentication
- Custom headers
- Multi-factor authentication
It is usually added to the SecurityFilterChain.
Interview One-Liner: A Custom Authentication Filter implements project-specific authentication logic, such as JWT or API key validation.
Common storage options:
Browser
- HttpOnly Secure Cookie (Recommended)
- Local Storage
- Session Storage
Mobile Apps
- Secure storage provided by the operating system.
Best Practice
For web applications, store JWT in an HttpOnly Secure Cookie to reduce the risk of XSS attacks.
Interview One-Liner: JWT should preferably be stored in an HttpOnly Secure Cookie; Local Storage is common but has higher XSS risk.
Best Practices
- Use HTTPS.
- Keep Access Tokens short-lived.
- Use Refresh Tokens.
- Never store passwords in JWT.
- Validate signature and expiration.
- Store tokens securely.
- Use strong secret keys.
- Revoke tokens if required (e.g., blacklist on logout).
- Rotate signing keys when appropriate.
Interview One-Liner: Secure JWT by using HTTPS, short-lived tokens, refresh tokens, secure storage, and proper signature validation.
β Interview Revision (JWT)
- JWT is a stateless authentication mechanism.
- Structure: Header β Payload β Signature.
- Authentication flow: Login β Generate JWT β Client sends JWT β JWT Filter validates β SecurityContext β Controller.
- JWT is ideal for REST APIs and microservices.
- Access Tokens are short-lived; Refresh Tokens generate new Access Tokens.
- JWT filters usually extend OncePerRequestFilter.
- Store JWT securely (prefer HttpOnly Secure Cookies for browsers).
- Always validate signature and expiration.
Spring Security Interview Questions & Answers
F. Session Management
Interview Tip: Session Management is often compared with JWT. Interviewers frequently ask, “Why do we use Session for web applications but JWT for REST APIs?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Stateful Authentication
The server stores user session information.
Example:
Client
β
Session ID
β
Server Session
Stateless Authentication
The server stores no session.
Each request contains the JWT.
Client
β
JWT
β
Server
Comparison
| Stateful | Stateless |
|---|---|
| Server stores session | No server session |
| Session ID | JWT |
| Better for traditional web apps | Better for REST APIs |
| Harder to scale | Easier to scale |
Interview One-Liner: Stateful authentication stores sessions on the server, while stateless authentication validates every request independently using a token.
An HTTP Session stores user information on the server after successful login.
The client receives a Session ID (usually in a cookie) and sends it with future requests.
The server uses this Session ID to identify the user.
Interview One-Liner: An HTTP Session stores authenticated user information on the server and identifies users using a Session ID.
Spring Security allows control over session creation using SessionCreationPolicy.
Common options:
| Policy | Description |
|---|---|
| ALWAYS | Always create a session |
| IF_REQUIRED | Create only when needed (default) |
| NEVER | Do not create a session, but use an existing one |
| STATELESS | Never create or use a session |
JWT Example
sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
Interview One-Liner: SessionCreationPolicy controls how Spring Security creates and manages HTTP sessions. JWT-based APIs typically use STATELESS.
A Session Fixation Attack occurs when an attacker forces a user to use a known Session ID.
If the user logs in with that Session ID, the attacker may hijack the session.
Spring Security prevents this by generating a new Session ID after successful authentication.
Interview One-Liner: A Session Fixation Attack tricks users into using a known Session ID; Spring Security protects against it by changing the Session ID after login.
Concurrent Session Control limits the number of active sessions for a user.
Example:
- Allow only one active login.
- If the user logs in on another device, the previous session is invalidated or the new login is blocked, depending on configuration.
Interview One-Liner: Concurrent Session Control limits the number of active sessions a user can have simultaneously.
Remember Me allows users to remain logged in even after closing the browser.
Spring Security stores a Remember Me token (typically in a cookie). When the user returns, Spring validates the token and automatically authenticates them.
Interview One-Liner: Remember Me Authentication keeps users logged in using a long-lived token stored in a cookie.
When a user logs out, Spring Security:
- Invalidates the HTTP session (for session-based authentication).
- Clears the SecurityContext.
- Deletes authentication cookies (if configured).
For JWT-based applications, because the server is stateless, logout is usually handled by:
- Removing the JWT from the client.
- Optionally blacklisting or revoking the token until it expires.
Interview One-Liner: Logout clears the user’s authentication. In session-based apps, the session is invalidated; in JWT-based apps, the client removes the token and the server may optionally revoke it.
β Interview Revision (Session Management)
- Stateful authentication stores sessions on the server; Stateless authentication uses JWT.
- An HTTP Session stores authenticated user information on the server.
- SessionCreationPolicy.STATELESS is recommended for JWT-based REST APIs.
- Spring Security prevents Session Fixation by creating a new Session ID after login.
- Concurrent Session Control limits simultaneous user logins.
- Remember Me uses a persistent token to keep users logged in.
- Logout invalidates the session for stateful applications, while JWT applications typically remove or revoke the token.
G. Password Security
Interview Tip: Password security is a favorite topic in interviews. Interviewers often ask “Why BCrypt?”, “What is Salting?”, and “Can passwords be decrypted?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Passwords should never be stored in plain text because if the database is compromised, attackers can immediately see every user’s password.
Instead, passwords should be hashed using a strong hashing algorithm like BCrypt before storing them.
Example
β Plain Text
Username: john
Password: admin123
β Hashed Password
Username: john
Password: $2a$10$JdP8X...
Even if someone steals the database, they cannot directly know the original password.
Risks of Plain Text Passwords
- Database leak exposes all passwords.
- Users often reuse passwords across multiple websites.
- Easy target for attackers.
Interview One-Liner: Passwords should never be stored in plain text because anyone who gains database access can immediately read them. They should always be stored as secure hashes.
BCrypt is a password hashing algorithm recommended by Spring Security.
It converts a password into a one-way hash that cannot be reversed.
BCrypt automatically generates a random salt for every password and is intentionally slow, making brute-force attacks much harder.
Example
PasswordEncoder encoder = new BCryptPasswordEncoder;
String hash = encoder.encode("admin123");
Possible Output
$2a$10$Wv9HkJ5...
Even hashing the same password again produces a different hash because of the random salt.
Advantages
- Automatic salting
- Strong hashing algorithm
- Resistant to rainbow table attacks
- Configurable work factor (strength)
Interview One-Liner: BCrypt is the recommended password hashing algorithm in Spring Security because it automatically salts passwords and is designed to resist brute-force attacks.
Password hashing is the process of converting a password into a fixed-length hash using a one-way algorithm.
The original password cannot be recovered from the hash.
During login:
1. User enters the password.
2. Spring hashes the entered password.
3. The generated hash is compared with the stored hash.
Example
Password
β
Hash Function
β
Hashed Password
Interview One-Liner: Password hashing converts a password into a one-way hash that is stored instead of the original password.
A salt is a random value added to a password before hashing.
This ensures that even if two users have the same password, their stored hashes are different.
Example
Without Salt
admin123 β ABC123
admin123 β ABC123
With Salt
admin123 + Salt1 β XYZ111
admin123 + Salt2 β LMN222
Benefits
- Prevents rainbow table attacks.
- Produces unique hashes for identical passwords.
- Improves password security.
Interview One-Liner: Salting adds a random value before hashing so identical passwords produce different hashes.
Adaptive hashing allows the hashing algorithm to become more computationally expensive over time.
As computers become faster, the work factor can be increased to maintain security.
BCrypt supports adaptive hashing through its strength (cost factor).
Example
new BCryptPasswordEncoder(12);
A higher cost factor means:
- More CPU time.
- Better protection.
- Slower brute-force attacks.
Interview One-Liner: Adaptive hashing allows the hashing algorithm’s work factor to be increased over time, making password cracking more difficult.
Spring Security provides multiple PasswordEncoder implementations.
| PasswordEncoder | Description |
|---|---|
| BCryptPasswordEncoder | Recommended for production |
| NoOpPasswordEncoder | No hashing (only for testing) |
| Pbkdf2PasswordEncoder | PBKDF2 algorithm |
| SCryptPasswordEncoder | SCrypt algorithm |
| Argon2PasswordEncoder | Argon2 algorithm (modern and secure) |
Recommendation
For most Spring Boot applications:
new BCryptPasswordEncoder;
Interview One-Liner: Spring Security provides several PasswordEncoder implementations, but BCryptPasswordEncoder is the most commonly used in production.
A Password Migration Strategy is used when upgrading from an old hashing algorithm (like MD5 or SHA-1) to a stronger one such as BCrypt.
Instead of forcing every user to reset their password immediately:
1. Support both old and new hash formats.
2. Authenticate users using the old hash.
3. Re-hash the password with BCrypt after a successful login.
4. Store the new BCrypt hash.
DelegatingPasswordEncoder helps support multiple hashing algorithms during migration.
Interview One-Liner: Password migration allows applications to move from weak hashing algorithms to stronger ones without forcing all users to reset their passwords immediately.
β Interview Revision (Password Security)
- Never store passwords in plain text.
- Store passwords as secure hashes.
- BCrypt is the recommended hashing algorithm.
- Salting ensures identical passwords have different hashes.
- Adaptive hashing increases security over time by raising the work factor.
- Spring Security provides multiple PasswordEncoder implementations.
- DelegatingPasswordEncoder supports smooth password migration.
Spring Security Interview Questions & Answers
H. CSRF, CORS & Security Attacks
Interview Tip: Interviewers frequently ask “What is the difference between CSRF and CORS?” and “Why do we disable CSRF in JWT-based REST APIs?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a logged-in user into sending an unwanted request to another website.
Because the browser automatically sends session cookies, the server may think the request is legitimate.
Example
A user is logged into a banking website.
A malicious website silently submits:
POST /transfer
Amount = βΉ10,000
The browser automatically sends the session cookie, and the transfer may be processed if no CSRF protection exists.
Interview One-Liner: CSRF is an attack where a malicious website tricks an authenticated user’s browser into sending unauthorized requests.
Spring Security generates a unique CSRF Token for each user session.
For state-changing requests (POST, PUT, DELETE, PATCH):
1. The client must send the CSRF token.
2. Spring compares it with the server-side token.
3. If they match, the request is allowed.
4. Otherwise, it is rejected.
Flow
User Login
β
CSRF Token Generated
β
POST Request + CSRF Token
β
Spring Validates Token
β
Allow / Reject
Interview One-Liner: Spring Security prevents CSRF by requiring a valid CSRF token for state-changing requests.
CSRF should generally be disabled for stateless REST APIs that use JWT because they do not rely on server-side sessions.
Example:
http.csrf(csrf -> csrf.disable);
For traditional web applications using session-based authentication, CSRF protection should remain enabled.
Interview One-Liner: Disable CSRF for stateless JWT-based REST APIs, but keep it enabled for session-based web applications.
Most REST APIs use JWT in the Authorization header instead of session cookies.
Since browsers do not automatically attach the Authorization header to cross-site requests, the risk of classic CSRF attacks is greatly reduced.
Therefore, many JWT-based REST APIs disable CSRF protection.
Interview One-Liner: JWT-based REST APIs commonly disable CSRF because authentication is performed using tokens instead of server-side sessions.
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a web page can make requests to a different origin.
Without proper CORS configuration, browsers block such requests.
Example
Frontend:
http://localhost:3000
Backend:
http://localhost:8080
Different ports mean different origins, so CORS must allow the request.
Interview One-Liner: CORS allows or blocks cross-origin browser requests based on the server’s configuration.
The Same Origin Policy is a browser security rule that blocks web pages from accessing resources on a different origin unless explicitly allowed.
An origin consists of:
- Protocol
- Domain
- Port
Example
https://example.com:443
Changing any one of these creates a different origin.
Interview One-Liner: The Same Origin Policy prevents browsers from accessing resources from different origins unless permitted through CORS.
A Preflight Request is an automatic HTTP OPTIONS request sent by the browser before certain cross-origin requests.
The browser checks whether the server allows the actual request.
If approved, the browser sends the original request.
Flow
Browser
β
OPTIONS Request
β
Server
β
CORS Allowed?
β
Yes
β
Actual Request
Interview One-Liner: A preflight request is an OPTIONS request used by browsers to verify CORS permissions before sending the actual request.
CORS can be configured in Spring Security or through Spring MVC.
Example:
http.cors(Customizer.withDefaults);
Or configure allowed origins, methods, and headers using a CorsConfigurationSource.
Interview One-Liner: CORS is configured by specifying which origins, HTTP methods, and headers are allowed to access the application.
XSS is an attack where an attacker injects malicious JavaScript into a web page.
When another user opens the page, the browser executes the script.
Prevention
- Validate user input.
- Escape HTML output.
- Use Content Security Policy (CSP).
- Avoid rendering untrusted HTML.
Interview One-Liner: XSS injects malicious JavaScript into web pages; it is prevented by validating input and safely rendering output.
SQL Injection occurs when attackers insert malicious SQL statements into application inputs.
Vulnerable Example
SELECT * FROM users
WHERE username='admin'
AND password='password'
If input is not validated, attackers may alter the query.
Prevention
- Prepared Statements
- Parameterized Queries
- JPA/Hibernate
- Input validation
Interview One-Liner: SQL Injection manipulates SQL queries using malicious input and is prevented using parameterized queries and ORM frameworks like JPA.
Clickjacking tricks users into clicking invisible or disguised elements embedded in another webpage.
This is often done using hidden iframes.
Prevention
- X-Frame-Options
- Content-Security-Policy (frame-ancestors)
Interview One-Liner: Clickjacking tricks users into clicking hidden content and is prevented using frame protection headers.
Security headers instruct browsers to enforce additional security rules.
Common headers include:
| Header | Purpose |
|---|---|
| X-Frame-Options | Prevent Clickjacking |
| Content-Security-Policy | Reduce XSS risk |
| X-Content-Type-Options | Prevent MIME type sniffing |
| Strict-Transport-Security (HSTS) | Force HTTPS |
| Referrer-Policy | Control referrer information |
Spring Security automatically configures several security headers by default.
Interview One-Liner: Security headers provide browser-level protection against attacks such as Clickjacking, XSS, MIME sniffing, and insecure HTTP connections.
β Interview Revision (CSRF, CORS & Security Attacks)
- CSRF tricks authenticated users into sending unwanted requests.
- Spring Security prevents CSRF using CSRF Tokens.
- Disable CSRF for stateless JWT REST APIs; keep it enabled for session-based applications.
- CORS controls cross-origin browser requests.
- Same Origin Policy blocks requests across different origins unless CORS allows them.
- Browsers send a Preflight (OPTIONS) request before certain cross-origin requests.
- XSS injects malicious JavaScript into web pages.
- SQL Injection manipulates SQL queries and is prevented with parameterized queries and JPA/Hibernate.
- Clickjacking tricks users into clicking hidden content.
- Security Headers add browser-level protections against common web attacks.
K. Filters
Interview Tip: Filters are among the most frequently asked Spring Security interview topics. Interviewers often ask “What is OncePerRequestFilter?”, “How do you implement JWT Authentication?”, and “How does the Security Filter Chain work?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
A Servlet Filter is part of the Java Servlet API and can intercept any HTTP request before it reaches the servlet.
A Spring Security Filter is a specialized filter used by Spring Security to perform authentication, authorization, CSRF protection, JWT validation, etc.
Comparison
| Servlet Filter | Spring Security Filter |
|---|---|
| Java Servlet API | Part of Spring Security |
| Can perform any request processing | Focuses on security |
| Configured by Servlet Container | Managed by Spring Security |
| Used for logging, compression, etc. | Used for authentication and authorization |
Example
Servlet Filter
Request
β
Logging Filter
β
Controller
Spring Security Filter
Request
β
JWT Filter
β
Authentication
β
Authorization
β
Controller
Interview One-Liner: Servlet Filters handle general request processing, while Spring Security Filters specifically implement security features like authentication and authorization.
A FilterChain is a sequence of filters through which every HTTP request passes before reaching the controller.
Each filter performs a specific task and then passes the request to the next filter.
Flow
Request
β
Filter 1
β
Filter 2
β
JWT Filter
β
Authorization Filter
β
Controller
Why is it important?
It allows Spring Security to:
- Authenticate users
- Validate JWT tokens
- Check permissions
- Handle exceptions
Interview One-Liner: FilterChain is a sequence of filters that process every request before it reaches the controller.
OncePerRequestFilter is a Spring Security base class that guarantees a filter executes only once for each HTTP request.
It is the most common base class for JWT Authentication Filters.
Example
public class JwtAuthenticationFilter
extends OncePerRequestFilter {
}
Why use it?
Without it, the same filter may execute multiple times during one request.
Interview One-Liner: OncePerRequestFilter ensures that a filter executes only once for each request.
GenericFilterBean is a Spring-provided base class for creating custom filters.
Unlike OncePerRequestFilter, it does not guarantee that the filter executes only once.
Difference
| GenericFilterBean | OncePerRequestFilter |
|---|---|
| Can execute multiple times | Executes only once |
| General-purpose filter | Preferred for JWT filters |
Interview One-Liner: GenericFilterBean is a base class for custom filters, while OncePerRequestFilter is preferred when the filter should execute only once.
UsernamePasswordAuthenticationFilter processes username/password login requests.
It:
1. Reads username and password.
2. Creates an Authentication object.
3. Calls the AuthenticationManager.
4. On success, stores authentication in the SecurityContext.
Flow
Login Request
β
UsernamePasswordAuthenticationFilter
β
AuthenticationManager
β
Authentication Success
Interview One-Liner: UsernamePasswordAuthenticationFilter authenticates users using their username and password during login.
BasicAuthenticationFilter supports HTTP Basic Authentication.
The client sends credentials in every request using the Authorization header.
Example:
Authorization: Basic dXNlcjpwYXNzd29yZA==
The credentials are Base64 encoded, not encrypted, so HTTPS should always be used.
Interview One-Liner: BasicAuthenticationFilter authenticates requests using HTTP Basic Authentication credentials.
BearerTokenAuthenticationFilter processes Bearer Tokens, typically OAuth2 or JWT tokens.
It:
1. Reads the Authorization header.
2. Extracts the Bearer token.
3. Validates the token.
4. Authenticates the user.
Example
Authorization: Bearer eyJhbGciOi...
Interview One-Liner: BearerTokenAuthenticationFilter authenticates requests using Bearer tokens such as JWTs.
ExceptionTranslationFilter handles security-related exceptions thrown by filters later in the chain.
It converts exceptions into appropriate HTTP responses.
Example
If authentication fails:
401 Unauthorized
If authorization fails:
403 Forbidden
Responsibilities
- Handle AuthenticationException
- Handle AccessDeniedException
- Invoke AuthenticationEntryPoint
- Invoke AccessDeniedHandler
Interview One-Liner: ExceptionTranslationFilter catches security exceptions and converts them into appropriate HTTP responses.
Spring Security executes filters in a predefined order.
Correct ordering is important because each filter depends on the output of previous filters.
For example:
Request
β
JWT Filter
β
UsernamePasswordAuthenticationFilter
β
Authorization Filter
β
Controller
When adding custom filters, we specify where they should execute.
Example:
http.addFilterBefore(jwtFilter,
UsernamePasswordAuthenticationFilter.class);
Interview One-Liner: Filter order determines the sequence in which security filters execute. Custom filters are usually added before or after existing filters.
A Custom Filter is created when the built-in Spring Security filters do not meet project requirements.
Common use cases:
- JWT Authentication
- API Key validation
- Custom headers
- Request logging
- Multi-factor authentication
Most JWT filters extend OncePerRequestFilter.
Example
public class JwtAuthenticationFilter
extends OncePerRequestFilter {
}
Interview One-Liner: A Custom Filter implements application-specific security logic, such as JWT or API key authentication.
β Interview Revision (Filters)
- Servlet Filters handle general request processing.
- Spring Security Filters implement authentication and authorization.
- Every request passes through the FilterChain.
- OncePerRequestFilter executes once per request.
- GenericFilterBean is a general-purpose filter base class.
- UsernamePasswordAuthenticationFilter processes login requests.
- BasicAuthenticationFilter supports HTTP Basic Authentication.
- BearerTokenAuthenticationFilter authenticates Bearer/JWT tokens.
- ExceptionTranslationFilter converts security exceptions into HTTP responses.
- Custom filters are usually added using addFilterBefore or addFilterAfter.
Spring Security Interview Questions & Answers
L. Exception Handling
Interview Tip: Interviewers commonly ask “What’s the difference between AuthenticationException and AccessDeniedException?” and “How do you return custom JSON error responses in Spring Security?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
AuthenticationException occurs when authentication fails.
This means the user has not been successfully authenticated.
Common Reasons
- Invalid username
- Wrong password
- Expired JWT
- Invalid JWT
- Missing authentication token
Response
401 Unauthorized
Interview One-Liner: AuthenticationException occurs when user authentication fails, and Spring Security returns 401 Unauthorized.
AccessDeniedException occurs when the user is already authenticated but does not have permission to access the requested resource.
Example
ROLE_USER
Trying to access:
DELETE /users/10
Only ROLE_ADMIN can access it.
Response
403 Forbidden
Interview One-Liner: AccessDeniedException occurs when an authenticated user lacks the required permissions, resulting in 403 Forbidden.
AuthenticationEntryPoint handles authentication failures.
It is invoked when an unauthenticated user tries to access a protected resource.
It is commonly customized in REST APIs to return JSON instead of the default HTML login page.
Example Response
{
"status": 401,
"message": "Unauthorized"
}
Interview One-Liner: AuthenticationEntryPoint handles authentication failures and returns a 401 Unauthorized response.
AccessDeniedHandler handles authorization failures.
It is invoked when an authenticated user lacks the required role or authority.
Example Response
{
"status": 403,
"message": "Access Denied"
}
Interview One-Liner: AccessDeniedHandler handles authorization failures and returns a 403 Forbidden response.
In REST APIs, we usually return a consistent JSON response instead of the default HTML error page.
Example:
{
"timestamp": "2026-07-27T10:30:00",
"status": 401,
"error": "Unauthorized",
"message": "Invalid JWT Token",
"path": "/api/orders"
}
This can be implemented using a custom AuthenticationEntryPoint and AccessDeniedHandler.
Benefits
- Consistent API responses
- Easier for frontend applications to handle errors
- Better debugging and logging
Interview One-Liner: Custom error responses provide consistent JSON responses for authentication and authorization failures.
In Spring Boot, business exceptions are typically handled using @ControllerAdvice and @ExceptionHandler.
However, security exceptions occur before the request reaches the controller, inside the Spring Security filter chain.
Therefore:
- AuthenticationException β handled by AuthenticationEntryPoint
- AccessDeniedException β handled by AccessDeniedHandler
@ControllerAdvice is not responsible for handling these security exceptions.
Flow
Request
β
Security Filter Chain
β
AuthenticationException
β
AuthenticationEntryPoint
β
401 Response
OR
Request
β
Security Filter Chain
β
AccessDeniedException
β
AccessDeniedHandler
β
403 Response
Interview One-Liner: Security exceptions are handled inside the Spring Security filter chain using AuthenticationEntryPoint and AccessDeniedHandler, not by @ControllerAdvice.
β Interview Revision (Exception Handling)
- AuthenticationException β User is not authenticated β 401 Unauthorized.
- AccessDeniedException β User is authenticated but not authorized β 403 Forbidden.
- AuthenticationEntryPoint handles authentication failures.
- AccessDeniedHandler handles authorization failures.
- Use custom implementations to return consistent JSON error responses.
- @ControllerAdvice handles controller exceptions, while Spring Security handles authentication and authorization exceptions inside the filter chain before the request reaches the controller.
M. Method Security
Interview Tip: Method Security is frequently asked along with @PreAuthorize. Interviewers often ask “Why use Method Security when we already have URL-based security?”
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
@EnableMethodSecurity enables method-level security in Spring Security.
It allows us to use annotations like:
- @PreAuthorize
- @PostAuthorize
- @PreFilter
- @PostFilter
- @Secured
- @RolesAllowed
Without this annotation, these security annotations will not work.
Example
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}
Interview One-Liner: @EnableMethodSecurity enables method-level authorization annotations in Spring Security.
@PreAuthorize checks authorization before a method executes.
If the user doesn’t have permission, the method is never executed.
Example
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
}
Only Admin users can invoke this method.
Interview One-Liner: @PreAuthorize performs authorization before method execution using SpEL expressions.
@PostAuthorize performs authorization after the method executes.
It is useful when authorization depends on the returned object.
Example
@PostAuthorize("returnObject.username == authentication.name")
public User getUser(Long id) {
}
The method executes first, then Spring checks whether the returned user belongs to the logged-in user.
Interview One-Liner: @PostAuthorize checks authorization after method execution based on the returned result.
@PreFilter filters a collection before passing it to a method.
Only elements matching the condition are sent to the method.
Example
@PreFilter("filterObject.owner == authentication.name")
public void updateOrders(List<Order> orders) {
}
Only the logged-in user’s orders are processed.
Interview One-Liner: @PreFilter filters collection arguments before method execution.
@PostFilter filters a collection after the method returns.
Only authorized objects are returned to the client.
Example
@PostFilter("filterObject.owner == authentication.name")
public List<Order> getOrders {
}
Only the logged-in user’s orders are returned.
Interview One-Liner: @PostFilter filters collection results after method execution.
Custom Security Expressions allow developers to implement project-specific authorization logic.
They are useful when built-in expressions like hasRole are not sufficient.
Example
@PreAuthorize("@securityService.canEdit(#orderId)")
Spring calls the custom method canEdit to decide whether access should be granted.
When to Use
- Resource ownership checks
- Department-based access
- Organization-specific rules
Interview One-Liner: Custom Security Expressions implement application-specific authorization rules beyond the built-in expressions.
SpEL (Spring Expression Language) is used inside security annotations to define authorization rules.
Common Examples
@PreAuthorize("hasRole('ADMIN')")
@PreAuthorize("hasAuthority('READ_PRODUCT')")
@PreAuthorize("authentication.name == #username")
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
Advantages
- Flexible authorization
- Access method parameters
- Access Authentication object
- Call custom beans
Interview One-Liner: SpEL allows dynamic authorization rules using roles, authorities, method parameters, authentication details, and custom beans.
β Interview Revision (Method Security)
- @EnableMethodSecurity enables method-level security.
- @PreAuthorize checks before method execution.
- @PostAuthorize checks after method execution.
- @PreFilter filters input collections.
- @PostFilter filters returned collections.
- Custom Security Expressions allow business-specific authorization.
- SpEL is used to write dynamic authorization rules.
Spring Security Interview Questions & Answers
N. SecurityContext
Interview Tip: SecurityContext questions are common in interviews. Be prepared to explain where Spring Security stores the logged-in user.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
SecurityContextHolder is a utility class that provides access to the current user’s SecurityContext.
After successful authentication, Spring stores the authenticated user in the SecurityContext, which is accessed through SecurityContextHolder.
Example
Authentication auth = SecurityContextHolder
.getContext
.getAuthentication;
Interview One-Liner: SecurityContextHolder provides access to the authenticated user’s security information.
The Authentication object represents the currently authenticated user.
It contains:
- Principal (User)
- Credentials
- Authorities (Roles/Permissions)
- Authentication Status
Example
Authentication authentication =
SecurityContextHolder.getContext.getAuthentication;
Interview One-Liner: The Authentication object stores details of the currently authenticated user.
The logged-in user can be obtained from the SecurityContextHolder.
Example
Authentication auth =
SecurityContextHolder.getContext.getAuthentication;
String username = auth.getName;
Alternative
@AuthenticationPrincipal
UserDetails user
Interview One-Liner: The logged-in user can be accessed using SecurityContextHolder or @AuthenticationPrincipal.
Spring Security stores the SecurityContext in a ThreadLocal.
This ensures each request thread has its own authenticated user information.
One user’s authentication data is isolated from another user’s request.
Flow
Request 1 (Thread A)
β
SecurityContext A
Request 2 (Thread B)
β
SecurityContext B
Interview One-Liner: ThreadLocal ensures each request thread has its own independent SecurityContext.
MODE_THREADLOCAL is the default strategy used by SecurityContextHolder.
Each thread maintains its own SecurityContext.
It is suitable for most web applications.
Interview One-Liner: MODE_THREADLOCAL stores the SecurityContext separately for each thread and is the default strategy.
MODE_INHERITABLETHREADLOCAL allows child threads to inherit the parent thread’s SecurityContext.
This is useful when a request creates child threads that also need authentication information.
Example
Parent Thread
β
SecurityContext
β
Child Thread
The child thread receives a copy of the parent’s security context.
Interview One-Liner: MODE_INHERITABLETHREADLOCAL allows child threads to inherit the parent’s SecurityContext.
β Interview Revision (SecurityContext)
- SecurityContextHolder provides access to the current user’s security information.
- The Authentication object contains the user, credentials, and authorities.
- Logged-in users can be accessed using SecurityContextHolder or @AuthenticationPrincipal.
- Spring stores the SecurityContext in a ThreadLocal.
- MODE_THREADLOCAL is the default strategy.
- MODE_INHERITABLETHREADLOCAL allows child threads to inherit the parent’s SecurityContext.
Spring Security Interview Questions & Answers
O. Spring Security with Microservices
Interview Tip: Product companies frequently ask how Spring Security works in a microservices architecture. Focus on JWT, API Gateway, OAuth2, and service-to-service security.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
In a microservices architecture, users authenticate once with an Authentication Server.
After successful login, the server issues a JWT.
The client sends this JWT with every request, and each microservice validates it before processing the request.
Flow
Client
β
Login
β
Auth Server
β
JWT
β
API Gateway
β
Order Service
β
Payment Service
Interview One-Liner: In microservices, users authenticate once and use a JWT that each service validates independently.
The API Gateway is the entry point for client requests.
It commonly performs:
- JWT validation
- Authentication
- Rate limiting
- Routing
- Logging
If authentication fails, the request is rejected before reaching downstream services.
Interview One-Liner: The API Gateway authenticates incoming requests and forwards only valid requests to microservices.
Each microservice validates the JWT before processing the request.
Typical checks include:
- Signature validation
- Expiration check
- Issuer validation
- Audience validation (if configured)
After validation, the authenticated user is stored in the SecurityContext.
Interview One-Liner: Every microservice validates the JWT to ensure the request is authentic before executing business logic.
Centralized Authentication means a dedicated Authentication Server handles login for all applications and microservices.
Examples include:
- Keycloak
- Okta
- Auth0
- Azure AD
Microservices trust tokens issued by the Authentication Server instead of authenticating users themselves.
Interview One-Liner: Centralized Authentication uses a dedicated Identity Provider to authenticate users and issue tokens for all services.
Keycloak is an open-source Identity and Access Management (IAM) solution.
It provides:
- Login
- Single Sign-On (SSO)
- OAuth2
- OpenID Connect
- JWT Token Generation
- Role Management
Spring Boot integrates with Keycloak using OAuth2 Resource Server.
Interview One-Liner: Keycloak is an Identity Provider that manages authentication, authorization, SSO, and JWT-based security.
A Resource Server is a Spring Boot application that protects APIs using OAuth2 access tokens.
It validates JWT tokens issued by an Authorization Server.
Flow
Authorization Server
β
JWT
β
Resource Server
β
Protected APIs
Interview One-Liner: An OAuth2 Resource Server validates access tokens and secures protected APIs.
Token Propagation means forwarding the user’s JWT from one microservice to another.
Example:
Client
β
JWT
β
Order Service
β
Same JWT
β
Payment Service
This allows downstream services to identify the same authenticated user.
Interview One-Liner: Token Propagation forwards the user’s JWT between microservices to preserve the user’s identity.
Sometimes one microservice calls another without direct user interaction.
Common approaches include:
- OAuth2 Client Credentials Flow
- Mutual TLS (mTLS)
- API Keys (less preferred for internal systems)
Client Credentials is the most common OAuth2 approach because services authenticate using their own identity instead of a user’s token.
Interview One-Liner: Service-to-service authentication commonly uses OAuth2 Client Credentials or mTLS to securely identify calling services.
When using Feign Client, the JWT from the incoming request is often added to the outgoing request.
This is typically done using a RequestInterceptor.
The interceptor reads the current JWT and adds it to the Authorization header.
Flow
Order Service
β
Feign Client
β
Authorization: Bearer <JWT>
β
Payment Service
Interview One-Liner: Feign Client security is commonly implemented using a RequestInterceptor that propagates the JWT to downstream services.
Best practices include:
- Use HTTPS or mTLS.
- Validate JWTs in every service.
- Use OAuth2 Client Credentials for service identities.
- Apply least-privilege access.
- Secure service secrets.
- Rotate keys regularly.
- Avoid trusting internal networks blindly.
Interview One-Liner: Secure inter-service communication using HTTPS/mTLS, JWT validation, OAuth2 Client Credentials, and least-privilege access.
β Interview Revision (Microservices)
- Authenticate users once and issue a JWT.
- The API Gateway authenticates requests before routing them.
- Each microservice validates the JWT independently.
- Use a centralized Identity Provider like Keycloak.
- Spring Boot APIs commonly act as OAuth2 Resource Servers.
- Use Token Propagation when one service calls another on behalf of a user.
- Use OAuth2 Client Credentials or mTLS for service-to-service authentication.
- Secure Feign Client calls using a RequestInterceptor to forward the JWT.
- Protect inter-service communication with HTTPS, token validation, and least-privilege security.
P. Production Best Practices
Interview Tip: These questions test your real-world experience. Always explain what you do in production and why.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
JWT is preferred in modern REST APIs because it is stateless.
The server does not store user sessions. Instead, each request contains the JWT, which is validated independently.
JWT vs Session
| JWT | Session |
|---|---|
| Stateless | Stateful |
| No server session | Session stored on server |
| Better scalability | Limited scalability |
| Best for Microservices | Best for Traditional Web Apps |
Production Use
- REST APIs β JWT
- Microservices β JWT
- Traditional MVC Applications β Session
Interview One-Liner: JWT is preferred for REST APIs because it is stateless, scalable, and ideal for distributed microservices.
In production, we secure REST APIs using multiple layers.
Best Practices
- JWT Authentication
- HTTPS
- Role-based Authorization
- Validate every JWT
- Input Validation
- Rate Limiting
- Secure Headers
- Proper Exception Handling
- Audit Logging
Interview One-Liner: Secure REST APIs using JWT, HTTPS, role-based authorization, input validation, rate limiting, and secure headers.
Sensitive endpoints should have stricter security controls.
Example:
/admin/**
should only be accessible to Admin users.
Production Practices
- Role-based Authorization
- Method-level Security (@PreAuthorize)
- JWT Validation
- Audit Logging
- Rate Limiting
- HTTPS
Example
@PreAuthorize("hasRole('ADMIN')")
Interview One-Liner: Sensitive endpoints should be protected using role-based authorization, JWT validation, HTTPS, and audit logging.
Browser
Recommended
- HttpOnly Secure Cookie
Alternative
- Local Storage
- Session Storage
Mobile
- Android Keystore
- iOS Keychain
Why HttpOnly Cookie?
- Not accessible through JavaScript.
- Reduces XSS risk.
- Works well with Secure and SameSite attributes.
Interview One-Liner: In web applications, JWT should preferably be stored in an HttpOnly Secure Cookie to reduce XSS risk.
| Cookie | Local Storage |
|---|---|
| HttpOnly supported | No |
| Better against XSS | Vulnerable to XSS |
| Automatically sent with requests | Sent manually in headers |
| Can use Secure & SameSite | Cannot |
Which one is better?
For browser-based applications:
HttpOnly Secure Cookie is generally preferred.
For SPAs, Local Storage is sometimes used, but additional XSS protection is essential.
Interview One-Liner: HttpOnly Secure Cookies are generally safer than Local Storage because JavaScript cannot access them.
- Keep Access Tokens short-lived (10β30 minutes).
- Store Refresh Tokens securely.
- Rotate Refresh Tokens after use.
- Revoke Refresh Tokens on logout or suspected compromise.
- Never expose Refresh Tokens in URLs.
Interview One-Liner: Use short-lived access tokens, securely stored refresh tokens, and rotate refresh tokens after each use.
A strong password policy should include:
- Minimum 8β12 characters
- Uppercase and lowercase letters
- Numbers
- Special characters
- Prevent common passwords
- Password hashing using BCrypt
- Optional Multi-Factor Authentication (MFA)
Interview One-Liner: Enforce strong passwords, hash them with BCrypt, and consider MFA for sensitive applications.
Secure headers help protect browsers from common attacks.
Common headers:
- Content-Security-Policy (CSP)
- X-Frame-Options
- X-Content-Type-Options
- Strict-Transport-Security (HSTS)
- Referrer-Policy
Spring Security configures several of these by default.
Interview One-Liner: Secure headers protect applications against browser-based attacks like XSS and Clickjacking.
HTTPS encrypts data exchanged between the client and server.
Without HTTPS:
- Passwords can be intercepted.
- JWTs can be stolen.
- Sensitive data can be exposed.
Production Practice
Always:
- Redirect HTTP β HTTPS.
- Enable HSTS.
- Use valid TLS certificates.
Interview One-Liner: HTTPS encrypts communication and protects passwords, tokens, and sensitive data from interception.
Applications use secrets such as:
- JWT Secret Keys
- Database Passwords
- API Keys
- OAuth Client Secrets
These should never be hardcoded.
Production Solutions
- Environment Variables
- Kubernetes Secrets
- AWS Secrets Manager
- HashiCorp Vault
- Azure Key Vault
Interview One-Liner: Secrets should never be hardcoded; they should be managed using secure secret management solutions.
Key Rotation means periodically replacing cryptographic keys.
Benefits:
- Limits the impact of a compromised key.
- Improves long-term security.
- Meets compliance requirements.
During rotation, applications may temporarily support both the old and new keys.
Interview One-Liner: Key Rotation periodically replaces encryption or signing keys to reduce security risks.
Security logging helps detect suspicious activity.
Examples:
- Failed logins
- Successful logins
- Password changes
- Role changes
- Token failures
- Account lockouts
Avoid logging sensitive information like passwords or full JWTs.
Interview One-Liner: Log important security events for monitoring and auditing, but never log passwords or sensitive tokens.
Rate Limiting restricts how many requests a client can make within a given time.
Example:
100 requests/minute
Benefits:
- Prevents abuse
- Reduces DDoS impact
- Protects APIs
Common tools:
- API Gateway
- Bucket4j
- Redis-based rate limiting
Interview One-Liner: Rate Limiting protects APIs by restricting excessive requests from clients.
Brute-force attacks repeatedly try different passwords until one succeeds.
Protection techniques:
- Account lock after multiple failed attempts.
- CAPTCHA after repeated failures.
- Rate Limiting.
- MFA.
- Temporary login delays.
Interview One-Liner: Brute-force protection prevents repeated login attempts using account lockouts, rate limiting, CAPTCHA, and MFA.
β Interview Revision (Production Best Practices)
- Prefer JWT for REST APIs and microservices.
- Protect APIs using JWT, HTTPS, RBAC, and input validation.
- Store JWT in HttpOnly Secure Cookies when possible.
- Use short-lived Access Tokens and rotating Refresh Tokens.
- Hash passwords with BCrypt.
- Use secure HTTP headers and enforce HTTPS.
- Never hardcode secrets; use secret managers.
- Rotate signing keys periodically.
- Log important security events without exposing sensitive data.
- Implement rate limiting and brute-force protection.
Spring Security Interview Questions & Answers
Q. Spring Security Internals
Interview Tip: Senior interviewers often ask “Explain the complete authentication flow” or “What happens internally when a request reaches Spring Security?” Understanding the sequence is more important than memorizing class names.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Authentication verifies the user’s identity.
Flow
Client
β
Login Request
β
UsernamePasswordAuthenticationFilter
β
AuthenticationManager
β
AuthenticationProvider
β
UserDetailsService
β
Database
β
PasswordEncoder
β
Authentication Success
β
SecurityContext
Step-by-Step
1. User submits username and password.
2. UsernamePasswordAuthenticationFilter creates an unauthenticated Authentication object.
3. AuthenticationManager receives it.
4. AuthenticationManager delegates to an AuthenticationProvider.
5. UserDetailsService loads the user from the database.
6. PasswordEncoder compares passwords.
7. If valid, an authenticated Authentication object is created.
8. It is stored in the SecurityContext.
Interview One-Liner: Authentication flows from the filter to the AuthenticationManager, then to the AuthenticationProvider, UserDetailsService, and PasswordEncoder, finally storing the authenticated user in the SecurityContext.
Authorization determines whether an authenticated user can access a resource.
Flow
Authenticated Request
β
SecurityContext
β
Roles & Authorities
β
Authorization Check
β
Allow / Deny
If authorized:
- Controller executes.
Otherwise:
- 403 Forbidden is returned.
Interview One-Liner: Authorization checks the authenticated user’s roles and authorities before allowing access to a resource.
Every HTTP request first passes through the SecurityFilterChain.
Each filter performs a specific task.
Typical flow:
Request
β
JWT Filter
β
Authentication Filter
β
Authorization Filter
β
ExceptionTranslationFilter
β
Controller
If any filter rejects the request, it never reaches the controller.
Interview One-Liner: SecurityFilterChain intercepts every request and executes security filters before the controller is called.
AuthenticationManager coordinates authentication.
It does not authenticate users itself. Instead, it delegates the request to one or more AuthenticationProvider implementations.
Flow
AuthenticationManager
β
AuthenticationProvider
β
Authentication Result
Interview One-Liner: AuthenticationManager delegates authentication requests to the appropriate AuthenticationProvider.
AuthenticationProvider performs the actual credential validation.
Responsibilities:
- Load user details.
- Verify passwords.
- Return an authenticated Authentication object.
The default implementation for username/password login is DaoAuthenticationProvider.
Interview One-Liner: AuthenticationProvider validates credentials and returns an authenticated user.
UserDetailsService is invoked by DaoAuthenticationProvider.
Sequence:
AuthenticationManager
β
DaoAuthenticationProvider
β
UserDetailsService
β
Database
loadUserByUsername loads the user and returns a UserDetails object.
Interview One-Liner: DaoAuthenticationProvider calls UserDetailsService to load user details from the database.
After the user is loaded, PasswordEncoder compares:
- The raw password entered by the user.
- The hashed password stored in the database.
Example:
passwordEncoder.matches(rawPassword, encodedPassword);
If they match, authentication succeeds.
Interview One-Liner: PasswordEncoder compares the raw login password with the stored hashed password.
The JWT Filter typically extends OncePerRequestFilter.
For every request:
1. Read the Authorization header.
2. Extract the JWT.
3. Validate the signature and expiration.
4. Load user details (if required).
5. Create an authenticated Authentication object.
6. Store it in the SecurityContext.
7. Continue the filter chain.
Flow
Request
β
Authorization Header
β
Extract JWT
β
Validate Token
β
Create Authentication
β
SecurityContext
β
Controller
Interview One-Liner: The JWT Filter validates the token and stores the authenticated user in the SecurityContext before the request reaches the controller.
After successful authentication, Spring stores the Authentication object inside the SecurityContext.
The SecurityContext is then stored in the SecurityContextHolder.
By default, SecurityContextHolder uses ThreadLocal, so each request thread has its own authenticated user.
Flow
Authentication Success
β
Authentication Object
β
SecurityContext
β
SecurityContextHolder
β
ThreadLocal
Interview One-Liner: SecurityContextHolder stores the authenticated user’s Authentication object in a thread-local SecurityContext.
AccessDecisionManager was responsible for deciding whether an authenticated user could access a protected resource.
It evaluated:
- Roles
- Authorities
- Security expressions
In Spring Security 6, it has largely been replaced by the newer AuthorizationManager API.
You may still encounter AccessDecisionManager in older projects based on Spring Security 5.
Interview One-Liner: AccessDecisionManager is the legacy authorization component that has largely been replaced by AuthorizationManager in Spring Security 6.
SecurityContext Persistence determines how the authenticated user’s SecurityContext is maintained between requests.
- Session-based applications: The SecurityContext is stored in the HTTP session, so the user remains logged in across requests.
- JWT-based stateless applications: The server does not persist the SecurityContext. Each request recreates it after validating the JWT.
Comparison
| Session Authentication | JWT Authentication |
|---|---|
| SecurityContext stored in HTTP Session | Recreated on every request |
| Stateful | Stateless |
| Session ID identifies the user | JWT identifies the user |
Interview One-Liner: In session-based applications, the SecurityContext is stored in the HTTP session. In JWT-based applications, it is recreated for every request after token validation.
β Interview Revision (Spring Security Internals)
- Authentication Flow: Filter β AuthenticationManager β AuthenticationProvider β UserDetailsService β PasswordEncoder β SecurityContext.
- Authorization Flow: SecurityContext β Roles/Authorities β Access Decision β Allow or Deny.
- Every request passes through the SecurityFilterChain.
- AuthenticationManager coordinates authentication by delegating to an AuthenticationProvider.
- DaoAuthenticationProvider calls UserDetailsService and uses PasswordEncoder to verify credentials.
- JWT Filters (usually extending OncePerRequestFilter) validate the token and populate the SecurityContext.
- SecurityContextHolder stores the authenticated user using ThreadLocal by default.
- AccessDecisionManager is a legacy authorization component; modern Spring Security uses AuthorizationManager.
- Session-based applications persist the SecurityContext in the HTTP session, while JWT-based applications recreate it for every request.
R. Spring Boot 3 / Spring Security 6 Changes
Interview Tip: Almost every Spring Boot 3 interview includes at least one migration question. Be ready to explain what changed in Spring Security 6 and why.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
Before Spring Security 6, we secured applications by extending WebSecurityConfigurerAdapter.
From Spring Security 6, it has been removed in favor of component-based configuration using SecurityFilterChain.
This makes the configuration:
- More readable
- More flexible
- Easier to customize
- Better aligned with Spring Boot’s bean-based configuration
Old Approach
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
New Approach
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
return http.build;
}
Interview One-Liner: WebSecurityConfigurerAdapter was removed in Spring Security 6 and replaced by bean-based configuration using SecurityFilterChain.
SecurityFilterChain is the primary configuration component in Spring Security 6.
It defines:
- Authentication
- Authorization
- Session Management
- CSRF
- CORS
- Custom Filters
Every HTTP request passes through this filter chain.
Example
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.authorizeHttpRequests(auth -> auth
.anyRequest.authenticated);
return http.build;
}
Interview One-Liner: SecurityFilterChain is the main Spring Security 6 configuration bean that defines how requests are secured.
authorizeRequests was used in older Spring Security versions.
Spring Security 6 replaces it with:
authorizeHttpRequests
Both configure authorization rules, but authorizeHttpRequests is the modern API.
Example
Old
http.authorizeRequests
New
http.authorizeHttpRequests
Interview One-Liner: authorizeHttpRequests replaces the older authorizeRequests method in Spring Security 6.
Earlier versions used:
.antMatchers("/admin/**")
Spring Security 6 uses:
.requestMatchers("/admin/**")
requestMatchers is more flexible and supports different request matching strategies.
Example
.requestMatchers("/admin/**")
.hasRole("ADMIN")
Interview One-Liner: requestMatchers replaces antMatchers in Spring Security 6.
Earlier versions used:
@EnableGlobalMethodSecurity
Spring Security 6 replaces it with:
@EnableMethodSecurity
It enables annotations such as:
- @PreAuthorize
- @PostAuthorize
- @Secured
- @RolesAllowed
Interview One-Liner: @EnableMethodSecurity replaces @EnableGlobalMethodSecurity in Spring Security 6.
Spring Security 6 recommends configuring security using Lambda DSL instead of chained method calls.
It improves readability and reduces nested configuration.
Example
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll
.anyRequest.authenticated);
Benefits
- Cleaner syntax
- Easier to read
- Easier to maintain
- Type-safe configuration
Interview One-Liner: Lambda DSL is the recommended way to configure Spring Security 6 because it provides cleaner and more readable configuration.
JWT-based REST APIs should not create HTTP sessions.
Configure:
http.sessionManagement(session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS
));
Also:
- Disable CSRF (for JWT APIs).
- Add the JWT filter.
- Validate every request.
Production Flow
Client
β
JWT
β
Security Filter Chain
β
JWT Filter
β
Controller
Interview One-Liner: Stateless security disables HTTP sessions and authenticates every request using a JWT.
β Interview Revision (Spring Boot 3 / Spring Security 6)
- WebSecurityConfigurerAdapter β Removed.
- SecurityFilterChain β New configuration approach.
- authorizeRequests β authorizeHttpRequests.
- antMatchers β requestMatchers.
- @EnableGlobalMethodSecurity β @EnableMethodSecurity.
- Lambda DSL is the recommended configuration style.
- JWT APIs should use SessionCreationPolicy.STATELESS.
Spring Security Interview Questions & Answers
S. Production Scenario Questions
Interview Tip: These questions evaluate your practical experience. Structure your answer as Problem β Solution β Why.
Expand a question to read the answer. Tick when youβre prepared (progress saved on this device).
For a banking application, I would implement multiple security layers instead of relying on just authentication.
Approach
- HTTPS for all communication.
- JWT or OAuth2 authentication.
- Multi-Factor Authentication (MFA) for login and high-value transactions.
- Role-Based Access Control (RBAC).
- Short-lived Access Tokens.
- Refresh Tokens.
- Rate Limiting.
- Account Lockout after repeated failed logins.
- Audit Logging.
- Encryption for sensitive data.
Interview One-Liner: A banking application should use layered security with HTTPS, JWT/OAuth2, MFA, RBAC, audit logging, and strong protection against attacks.
Steps
1. User logs in with username/password.
2. Authenticate using AuthenticationManager.
3. Load user using UserDetailsService.
4. Verify password using PasswordEncoder.
5. Generate JWT with user details and expiry.
6. Return JWT to the client.
7. Client sends JWT in the Authorization header.
8. JWT Filter validates the token.
9. Store authentication in SecurityContext.
10. Continue the request.
Interview One-Liner: Authenticate the user, generate a signed JWT, validate it in a custom JWT filter, and populate the SecurityContext for every request.
Access Tokens should expire quickly to reduce risk.
Refresh Tokens allow users to obtain a new Access Token without logging in again.
Benefits
- Better user experience.
- Improved security.
- Short-lived Access Tokens.
Interview One-Liner: Refresh Tokens allow secure renewal of short-lived Access Tokens without requiring users to log in again.
JWT is stateless, so simply logging out does not invalidate an already-issued token.
Common approaches:
- Remove the token from the client.
- Maintain a token blacklist until expiry.
- Use short-lived Access Tokens with Refresh Tokens.
- Revoke Refresh Tokens on logout.
Interview One-Liner: Since JWT is stateless, logout is typically implemented by deleting the client token and revoking or blacklisting refresh tokens.
I would use an Identity Provider such as:
- Keycloak
- Okta
- Azure AD
Authentication is handled centrally using OAuth2/OpenID Connect.
Applications trust the Identity Provider instead of managing passwords independently.
Interview One-Liner: Implement SSO using an Identity Provider like Keycloak with OAuth2/OpenID Connect.
Steps
1. Configure a Realm in Keycloak.
2. Create Clients and Roles.
3. Configure Spring Boot as an OAuth2 Resource Server.
4. Validate JWT tokens.
5. Map Keycloak roles to Spring Security authorities.
Interview One-Liner: Configure Keycloak as the Identity Provider and Spring Boot as an OAuth2 Resource Server that validates Keycloak-issued JWTs.
Architecture
Client
β
API Gateway
β
JWT Validation
β
Microservices
Best Practices
- Authenticate at the API Gateway.
- Validate JWT at the Gateway and optionally again in each service (defense in depth).
- Use HTTPS.
- Apply Rate Limiting.
- Forward user identity securely.
Interview One-Liner: Authenticate requests at the API Gateway and let each microservice validate the JWT before processing requests.
Create roles such as:
- ADMIN
- USER
- MANAGER
Assign permissions to roles.
Protect APIs using:
@PreAuthorize("hasRole('ADMIN')")
Interview One-Liner: RBAC assigns permissions to roles, and users inherit permissions through their assigned roles.
Instead of checking only roles, define fine-grained permissions.
Example:
- READ_PRODUCT
- CREATE_PRODUCT
- DELETE_PRODUCT
Protect APIs using:
@PreAuthorize("hasAuthority('DELETE_PRODUCT')")
Interview One-Liner: Permission-based authorization checks specific authorities rather than broad roles.
Best Practices
- Admin role only.
- JWT validation.
- MFA for sensitive operations.
- Audit logging.
- IP restrictions (if required).
- Rate Limiting.
Example
@PreAuthorize("hasRole('ADMIN')")
Interview One-Liner: Protect Admin APIs using RBAC, JWT validation, MFA for critical actions, and audit logging.
Techniques
- Account Lockout.
- Rate Limiting.
- CAPTCHA.
- Temporary delays after failures.
- MFA.
Interview One-Liner: Prevent brute-force attacks using account lockout, rate limiting, CAPTCHA, and MFA.
Authentication should occur in two steps:
1. Username & Password.
2. OTP, Authenticator App, or Push Notification.
The user is granted access only after both factors are verified.
Interview One-Liner: MFA requires users to verify both their password and a second authentication factor before granting access.
A common production approach is:
1. Generate a new signing key.
2. Start signing new JWTs with the new key.
3. Continue accepting tokens signed by both the old and new keys until old tokens expire.
4. Remove the old key after all old tokens have expired.
Using a Key ID (kid) in the JWT header helps identify which key should be used for verification.
Interview One-Liner: Rotate JWT signing keys by supporting both old and new keys during a transition period, then retire the old key after existing tokens expire.
Best Practices
- HTTPS or mTLS.
- OAuth2 Client Credentials.
- JWT validation.
- Secret Management.
- Least Privilege Access.
Interview One-Liner: Secure service-to-service communication using HTTPS/mTLS, OAuth2 Client Credentials, and JWT validation.
Use a RequestInterceptor to add the current JWT (or a service access token) to the outgoing request.
Order Service
β
Feign Client
β
Authorization: Bearer <JWT>
β
Payment Service
Interview One-Liner: Use a Feign RequestInterceptor to propagate the JWT or service token in the Authorization header.
Best Practices
- Authenticate the user.
- Authorize upload permissions.
- Validate file type.
- Validate file size.
- Rename uploaded files.
- Store files outside the web root or in secure object storage.
- Scan uploads for malware if required.
- Restrict executable file uploads.
Interview One-Liner: Secure file uploads by validating users, file type, file size, storage location, and scanning for malicious content.
Steps
1. Track failed login attempts.
2. Increment the failure count after each unsuccessful login.
3. Lock the account after a configurable threshold (for example, 5 failed attempts).
4. Unlock after a timeout or through an administrator/password reset.
5. Log the event and notify the user if appropriate.
Interview One-Liner: Track failed logins, lock the account after repeated failures, and automatically unlock it after a defined period or administrative action.
β Interview Revision (Production Scenarios)
- Use layered security for banking applications: HTTPS, JWT/OAuth2, MFA, RBAC, audit logs.
- JWT authentication flow: Login β Authenticate β Generate JWT β Validate JWT β Populate SecurityContext.
- Use Refresh Tokens with short-lived Access Tokens.
- Handle JWT logout by removing client tokens and revoking/blacklisting refresh tokens.
- Implement SSO using Keycloak or another OAuth2/OpenID Connect provider.
- Secure microservices with an API Gateway, JWT validation, and HTTPS.
- Use RBAC for broad access and permissions for fine-grained authorization.
- Protect admin APIs with RBAC, MFA for critical actions, audit logging, and rate limiting.
- Prevent brute-force attacks with account lockout, rate limiting, CAPTCHA, and MFA.
- Rotate JWT signing keys using overlapping key support and kid headers to avoid downtime.
- Secure service-to-service communication using HTTPS/mTLS and OAuth2 Client Credentials.
- Protect file uploads with authentication, validation, and secure storage.
- Implement account lockout by tracking failed login attempts and locking accounts after repeated failures.”,