Security is one of those topics that looks simple until you have to secure a real production application.
Adding a login screen is easy. Designing authentication and authorization for a distributed Spring Boot application is a completely different problem.
In a production microservices architecture, you may have an API gateway, multiple Spring Boot services, an identity provider, JWT access tokens, refresh tokens, role-based authorization, OAuth2 scopes, service-to-service communication, CORS, CSRF protection, rate limiting, and security auditing.
And when something goes wrong, a senior engineer is expected to understand not only what configuration to change, but also why the security system behaves that way.
This article covers 50 senior-level Spring Security, OAuth2, and JWT interview questions with answers. It starts with Spring Security fundamentals and moves into authentication, authorization, JWT, OAuth2, microservices security, and production architecture.
If you are preparing for a senior Java, Spring Boot, or microservices interview, this guide is designed to help you understand the concepts rather than simply memorize answers.
Spring Security is a security framework for Java applications, particularly applications built using Spring.
It provides mechanisms for authentication, authorization, protection against common web attacks, password management, session management, OAuth2, JWT-based resource servers, and more.
For a Spring Boot application, Spring Security can be used to protect REST APIs, web applications, and microservices.
A typical security flow looks like:
Client → Spring Security → Authentication → Authorization → Controller → Business Logic
Spring Security is primarily implemented around servlet filters in traditional Spring MVC applications.
Incoming HTTP requests pass through Spring Security's filter infrastructure before reaching the application controller.
The filters can perform tasks such as:
This is why understanding the filter chain is important for senior-level Spring Security interviews.
The SecurityFilterChain defines which Spring Security filters apply to a request.
Spring Security uses a FilterChainProxy to delegate requests to the appropriate security filter chain.
Different filters perform different responsibilities such as authentication, authorization, exploit protection, request handling, and security context management.
A simplified flow is:
HTTP Request → FilterChainProxy → SecurityFilterChain → Security Filters → Controller
The exact filters depend on the application's configuration.
Authentication answers:
"Who are you?"
Authorization answers:
"What are you allowed to do?"
For example, when a user logs in successfully, authentication establishes the user's identity.
Authorization then determines whether that user can access an admin API.
SecurityContext contains the security information associated with the current execution context.
One of its most important pieces of information is the current Authentication object.
After successful authentication, Spring Security can store information such as the authenticated principal and granted authorities in the SecurityContext.
SecurityContextHolder is the primary mechanism used by Spring Security to associate a SecurityContext with the current execution.
Application code can use it to access the current authentication when appropriate.
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
In modern applications, developers should understand the context propagation model, especially when working with asynchronous execution or reactive applications.
UserDetailsService is an interface used by Spring Security to retrieve user information during username/password authentication.
A custom implementation might load a user from a database.
@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
// Load user from database
return ...;
}
}
The returned UserDetails contains information such as username, password, account status, and authorities.
PasswordEncoder is used to securely encode passwords instead of storing plaintext passwords.
A common implementation is BCryptPasswordEncoder.
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Passwords should never be stored as plaintext, and application developers should avoid implementing password hashing algorithms themselves.
Both BCrypt and PBKDF2 are password hashing approaches designed to make password guessing more expensive.
BCrypt is widely used in Java applications and includes a configurable work factor.
PBKDF2 derives a key through repeated hashing operations and allows configuration of iterations and other parameters.
The important production consideration is not simply choosing the algorithm. You should use a well-tested password hashing implementation with appropriate parameters and keep those parameters aligned with your security requirements.
Authentication can be customized in several ways depending on the application's requirements.
For username/password authentication, you may customize:
For JWT-based APIs, authentication usually involves configuring the application as an OAuth2 Resource Server and validating bearer tokens issued by an authorization server.
Spring Security supports multiple authentication approaches.
Depending on the application, these can include:
The right approach depends on whether you are building a browser application, REST API, mobile application, or distributed microservices platform.
Form Login is commonly used for browser-based applications where users interact with a login page.
HTTP Basic sends credentials using the Authorization header for each request.
Basic authentication should always be protected with HTTPS because credentials must not travel over an unencrypted connection.
For modern REST APIs, OAuth2 bearer tokens are often more appropriate than Basic authentication.
In stateful authentication, the server maintains authentication state, commonly through an HTTP session.
In stateless authentication, each request contains the information needed for authentication, commonly through a bearer token.
JWT-based API authentication is often designed to be stateless.
However, stateless does not automatically mean secure or scalable. Token lifetime, revocation strategy, key management, storage, and authorization still need careful design.
RBAC controls access based on roles assigned to users or identities.
For example:
An endpoint might allow only users with the ADMIN role.
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/reports")
public Report getReports() {
return ...;
}
Method-level security allows authorization rules to be applied directly to service methods.
This is useful when authorization needs to be enforced close to business operations rather than only at the HTTP endpoint level.
For example:
@PreAuthorize("hasAuthority('order:read')")
public Order getOrder(Long id) {
return ...;
}
This approach can provide an additional authorization boundary inside the application.
@PreAuthorize evaluates an authorization expression before a method executes.
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long userId) {
...
}
You can also use method parameters and authorities in expressions when implementing more complex authorization rules.
@PostAuthorize evaluates an authorization expression after the method has executed but before the result is returned to the caller.
This can be useful when authorization depends on the returned object.
@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) {
return ...
}
It should be used carefully because the method has already executed before authorization is evaluated.
@Secured is an annotation that can be used to restrict access to methods based on configured security attributes.
@Secured("ROLE_ADMIN")
public void deleteAccount() {
...
}
For more expressive authorization rules, @PreAuthorize is generally more flexible because it supports authorization expressions.
A production REST API should typically include multiple layers of protection.
Depending on the architecture, these may include:
Authentication alone is not enough. The API must also determine what the authenticated identity is allowed to do.
Microservices should not automatically trust every internal request simply because it originates from the internal network.
A common architecture includes:
Client → API Gateway → Authentication → Microservices → Protected Resources
Services can validate access tokens and enforce their own authorization rules.
For service-to-service communication, teams may also use workload identities, OAuth2 client credentials, mTLS, network policies, and other controls depending on the environment.
JWT stands for JSON Web Token.
It is a compact token format that can carry claims and can be digitally signed so that the receiving application can verify its integrity.
JWTs are commonly used as bearer access tokens in OAuth2-based systems.
A JWT has three parts separated by dots:
Header.Payload.Signature
The header contains metadata such as the signing algorithm.
The payload contains claims.
The signature allows the recipient to verify that the token has not been modified and was signed by a trusted key.
A trusted token issuer creates a JWT containing claims such as subject, issuer, audience, scopes, and expiration.
The token is then signed using an appropriate cryptographic key.
The client receives the access token and sends it to a protected API using the Authorization header.
Authorization: Bearer <access-token>
A resource server validates the incoming JWT before allowing access to protected resources.
Validation can include:
Spring Security's OAuth2 Resource Server support can automatically validate JWT bearer tokens when appropriately configured.
An access token is used to access protected resources.
A refresh token is used to obtain a new access token after the current access token expires, when the authorization server and client flow support refresh tokens.
Access tokens are generally short-lived, while refresh tokens may have a longer lifetime and therefore require stronger protection.
This is one of the important differences between self-contained tokens and server-side sessions.
A JWT can remain cryptographically valid until it expires unless the system introduces a revocation mechanism.
Possible approaches include:
The correct strategy depends on the application's security and operational requirements.
The answer depends on the type of application and its threat model.
For browser applications, token storage requires careful consideration because JavaScript-accessible storage can increase exposure to XSS attacks.
Secure, HttpOnly cookies can reduce JavaScript access but introduce other considerations such as CSRF protection and cookie configuration.
There is no universal "store every JWT here" answer. Token storage should be designed together with the application's authentication architecture and threat model.
Common risks include:
JWT is a token format, not a complete security architecture.
Access tokens should normally have an expiration time.
When the token expires, the client may use an appropriate refresh-token flow to obtain a new access token if supported.
For APIs, the resource server should reject expired tokens rather than silently accepting them.
Session authentication keeps authentication state on the server and normally gives the client a session identifier.
JWT authentication can carry claims inside the token and is commonly used for stateless APIs.
JWT can be useful for distributed systems, but it also introduces challenges such as token revocation, key rotation, token storage, and claim management.
The correct choice depends on the application architecture rather than simply assuming JWT is always better.
OAuth2 is an authorization framework that allows an application to obtain limited access to protected resources without directly handling the resource owner's credentials.
OAuth2 is commonly used for delegated authorization and API security.
For example, a client application can obtain an access token from an authorization server and then use that token to call a protected API.
OAuth2 and JWT are not competing technologies.
OAuth2 is an authorization framework.
JWT is a token format.
OAuth2 can use JWT access tokens, but OAuth2 does not require JWT. OAuth2 resource servers can also work with opaque access tokens.
The Authorization Code flow is commonly used when a client needs delegated access on behalf of a user.
A simplified flow is:
For public clients such as browser or mobile applications, PKCE is an important part of modern authorization-code deployments.
Scopes represent permissions requested or granted to a client.
For example:
A resource server can use scopes to determine whether a bearer token has sufficient permission to access an endpoint.
An Authorization Server authenticates clients or users and issues tokens according to the configured authorization flow.
It is responsible for token issuance and related authorization responsibilities.
Examples in real-world architectures include dedicated identity and authorization platforms or a custom authorization server implementation.
A Resource Server hosts protected resources such as REST APIs.
It receives access tokens and validates them before allowing access to protected resources.
In a Spring Boot microservices architecture, each microservice can potentially act as a resource server.
An Identity Provider is a system that manages user identities and authentication.
It can authenticate users and participate in OAuth2 and OpenID Connect flows.
Examples include enterprise identity platforms and identity servers such as Keycloak.
OAuth2 primarily addresses authorization.
OpenID Connect builds an identity layer on top of OAuth2 and provides standardized mechanisms for authentication and identity information.
A simple way to remember the distinction is:
OAuth2 → Authorization
OIDC → Authentication and Identity on top of OAuth2
A common modern approach is to configure the Spring Boot application as an OAuth2 Resource Server and point it to the Keycloak issuer.
For example:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://keycloak.example.com/realms/myrealm
Spring Security can use the issuer metadata to discover the appropriate keys and validate incoming JWTs.
The exact configuration depends on the Keycloak version, deployment model, and application requirements.
A typical architecture looks like:
Client → Authorization Server → Access Token → Resource Server
The API is configured as an OAuth2 Resource Server.
When a request contains a bearer token, Spring Security validates the token and creates the authenticated security context.
Authorization rules can then be applied using scopes, authorities, roles, or custom authorization logic.
CSRF stands for Cross-Site Request Forgery.
It occurs when a malicious site causes a user's browser to make an unwanted authenticated request to another application.
CSRF protection is particularly relevant to browser applications using cookie-based authentication.
For stateless APIs using bearer tokens in the Authorization header, CSRF considerations are different because browsers do not automatically attach the Authorization header in the same way they automatically send cookies.
The correct configuration depends on the authentication mechanism and client architecture.
CORS stands for Cross-Origin Resource Sharing.
It controls whether a browser is allowed to make requests from one origin to another origin.
For example, a frontend hosted at:
https://frontend.example.com
may need to call:
https://api.example.com
The backend must be configured to allow the required origin, methods, headers, and credentials according to the application's requirements.
CORS is a browser security mechanism and should not be confused with authentication or authorization.
XSS stands for Cross-Site Scripting.
Common defensive practices include:
For APIs, developers should also ensure that untrusted input is handled safely and is not reflected into HTML without proper encoding.
Rate limiting restricts how many requests a client can make within a defined period.
It can protect APIs against abuse, accidental traffic spikes, brute-force attempts, and certain denial-of-service scenarios.
Rate limiting can be implemented at different layers:
For microservices, centralized rate limiting at the gateway is often useful, while sensitive operations may also require application-level limits.
Signing-key rotation is an important part of production security.
With asymmetric signing, the authorization server can publish public keys through a JWK Set endpoint while keeping the private signing key protected.
During rotation, the authorization server can introduce a new key while retaining the previous public key long enough for valid existing tokens to be verified.
Resource servers can discover and use the appropriate public keys.
Key rotation should be planned carefully so that legitimate tokens are not unexpectedly rejected.
SSO allows users to authenticate once and access multiple applications without separately logging into each application.
A common architecture uses an Identity Provider with OpenID Connect.
The applications trust the Identity Provider and redirect users to it for authentication.
After successful authentication, the applications can establish their own application sessions or use tokens depending on the architecture.
Internal network access should not automatically be treated as proof of identity.
Depending on the environment, service-to-service security can use:
For highly sensitive systems, authentication, authorization, encryption, identity management, and network controls should work together.
Start by identifying exactly where the request is failing.
Check:
Spring Security debugging and logging can provide useful information about the security processing pipeline.
For JWT resource servers, inspect the token's issuer, audience, expiration, signature, scopes, and authority mapping.
This is an interview question where the interviewer is looking for your problem-solving approach rather than a theoretical definition.
A strong answer should follow a structure such as:
For example, if expired tokens were incorrectly accepted because of an authorization configuration issue, explain how the issue was detected, how token validation was corrected, and what monitoring or automated tests were added afterward.
This is one of the most important senior-level questions because it tests architecture rather than syntax.
A possible architecture is:
User → Frontend → Identity Provider → Access Token → API Gateway → Spring Boot Microservices → Databases/External Services
The Identity Provider handles authentication and token issuance.
The API Gateway can provide edge-level controls such as routing, rate limiting, and token enforcement.
Spring Boot services act as resource servers and independently validate access tokens where appropriate.
Authorization can then be enforced using:
A production architecture should also include:
This is a very common type of real-world Spring Security problem.
If the JWT is valid but the API returns 403 Forbidden, authentication may have succeeded while authorization failed.
I would investigate:
This distinction is important:
401 usually indicates an authentication problem.
403 usually indicates that the request was understood but access was not permitted.
| Concept | Simple Explanation |
|---|---|
| Authentication | Determines who the user or client is |
| Authorization | Determines what the identity can access |
| SecurityContext | Contains security information for the current execution |
| SecurityFilterChain | Defines the security filters applied to requests |
| JWT | A signed token format containing claims |
| OAuth2 | Authorization framework for delegated access |
| OIDC | Identity layer built on OAuth2 |
| Authorization Server | Issues tokens and handles authorization flows |
| Resource Server | Protects APIs and validates access tokens |
| Scope | Represents a permission granted to a client |
| RBAC | Authorization based on roles |
| CSRF | Attack involving unwanted authenticated browser requests |
| CORS | Browser mechanism controlling cross-origin requests |
| SSO | Single authentication experience across applications |
At a senior level, interviewers usually do not expect you to simply define JWT or OAuth2.
They want to know whether you can make good security decisions in a production system.
For example:
The strongest interview answers connect the technology to security, scalability, operational simplicity, and real production scenarios.
Spring Security, OAuth2, and JWT are much more than interview topics.
They are fundamental building blocks for securing modern Spring Boot applications and microservices.
A senior engineer should understand the complete security journey:
Identity → Authentication → Token → Validation → Authorization → Protected Resource
And when that architecture is deployed into production, security also needs to consider key rotation, token lifetime, rate limiting, audit logging, secure communication, monitoring, and incident response.
If you are building or modernizing a Java and Spring Boot microservices platform, security should be part of the architecture from the beginning rather than something added just before production.
Looking for practical Java, Spring Boot, microservices, AWS, and backend engineering content? Explore more technical guides from LogicBrace.
No. OAuth2 is an authorization framework, while JWT is a token format. OAuth2 systems can use JWT access tokens, but OAuth2 can also use opaque tokens.
JWT can be used securely, but a JWT itself does not make an application secure. Correct signature validation, key management, token expiration, storage, issuer and audience validation, and authorization are all important.
OAuth2 focuses on authorization, while OpenID Connect adds an identity and authentication layer on top of OAuth2.
That depends on the architecture. In many systems, services act as OAuth2 resource servers and validate tokens themselves. Other architectures may centralize some controls at an API gateway while still enforcing authorization at the service level.
Understanding how authentication, authorization, SecurityContext, filters, token validation, and application-level authorization work together is more valuable than memorizing individual configuration properties.
Which Spring Security, OAuth2, or JWT question has been asked in your interview?
Share it in the comments. We can add the most interesting real-world questions to future interview guides.
SEO Title: Spring Security, OAuth2 & JWT: 50 Senior Interview Questions and Answers
Meta Description: Prepare for senior Java interviews with 50 Spring Security, OAuth2 and JWT interview questions covering authentication, authorization, JWT, OAuth2, Keycloak, microservices security, CSRF, CORS and production architecture.
Suggested Labels: Spring Security, OAuth2, JWT, Spring Boot, Java, Microservices, Java Interview, Backend Engineering, Application Security
Suggested Image Alt Text: Spring Security OAuth2 JWT 50 senior interview questions and answers for Java developers
0 Comments