Spring Security, OAuth2 & JWT: 50 Senior Interview Questions and Answers


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 Fundamentals

1. What is Spring Security?

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

2. How does Spring Security work internally?

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:

  • Extracting credentials or bearer tokens
  • Authenticating the request
  • Creating an Authentication object
  • Populating the SecurityContext
  • Checking authorization rules
  • Handling authentication and authorization failures

This is why understanding the filter chain is important for senior-level Spring Security interviews.

3. Explain the Spring Security Filter Chain.

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.

4. Authentication vs Authorization?

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.

5. What is SecurityContext?

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.

6. What is SecurityContextHolder?

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.

7. What is UserDetailsService?

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.

8. What is PasswordEncoder?

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.

9. BCrypt vs PBKDF2?

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.

10. How do you customize authentication in Spring Security?

Authentication can be customized in several ways depending on the application's requirements.

For username/password authentication, you may customize:

  • UserDetailsService
  • PasswordEncoder
  • AuthenticationProvider
  • AuthenticationManager
  • Authentication filters

For JWT-based APIs, authentication usually involves configuring the application as an OAuth2 Resource Server and validating bearer tokens issued by an authorization server.

Authentication & Authorization

11. What are the different authentication mechanisms supported by Spring Security?

Spring Security supports multiple authentication approaches.

Depending on the application, these can include:

  • Username/password authentication
  • HTTP Basic authentication
  • Form login
  • OAuth2 login
  • OAuth2 Resource Server with JWT
  • Opaque token authentication
  • Remember-me authentication
  • Custom authentication mechanisms

The right approach depends on whether you are building a browser application, REST API, mobile application, or distributed microservices platform.

12. Form Login vs Basic Authentication?

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.

13. Stateless vs Stateful 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.

14. What is Role-Based Access Control (RBAC)?

RBAC controls access based on roles assigned to users or identities.

For example:

  • USER
  • MANAGER
  • ADMIN

An endpoint might allow only users with the ADMIN role.

@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/reports")
public Report getReports() {
    return ...;
}

15. How do you implement method-level security?

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.

16. What is @PreAuthorize?

@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.

17. What is @PostAuthorize?

@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.

18. What is @Secured?

@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.

19. How do you secure REST APIs?

A production REST API should typically include multiple layers of protection.

Depending on the architecture, these may include:

  • HTTPS
  • OAuth2 or JWT authentication
  • Authorization rules
  • Input validation
  • Rate limiting
  • CORS configuration
  • Security headers
  • Audit logging
  • Appropriate token expiration

Authentication alone is not enough. The API must also determine what the authenticated identity is allowed to do.

20. How do you secure microservices?

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 (JSON Web Token)

21. What is JWT?

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.

22. What are the three parts of a JWT?

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.

23. How is a JWT generated?

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>

24. How is a JWT validated?

A resource server validates the incoming JWT before allowing access to protected resources.

Validation can include:

  • Signature validation
  • Issuer validation
  • Expiration validation
  • Not-before validation
  • Audience validation where configured
  • Scope or authority mapping

Spring Security's OAuth2 Resource Server support can automatically validate JWT bearer tokens when appropriately configured.

25. Access Token vs Refresh Token?

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.

26. How do you invalidate a JWT?

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:

  • Short-lived access tokens
  • Refresh-token revocation
  • Token deny lists where necessary
  • Key rotation
  • Centralized authorization decisions

The correct strategy depends on the application's security and operational requirements.

27. Where should JWTs be stored?

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.

28. What are the security risks of JWT?

Common risks include:

  • Token theft
  • Long token lifetimes
  • Weak key management
  • Improper signature validation
  • Incorrect issuer or audience validation
  • Sensitive information placed in claims
  • Unsafe browser storage
  • Lack of revocation strategy

JWT is a token format, not a complete security architecture.

29. How do you handle token expiration?

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.

30. JWT vs Session Authentication?

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

31. What is OAuth2?

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.

32. OAuth2 vs JWT?

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.

33. Explain the OAuth2 Authorization Code Flow.

The Authorization Code flow is commonly used when a client needs delegated access on behalf of a user.

A simplified flow is:

  1. User accesses the client application.
  2. The client redirects the user to the authorization server.
  3. The user authenticates and grants consent if required.
  4. The authorization server returns an authorization code.
  5. The client exchanges the code for tokens.
  6. The client uses the access token to call protected APIs.

For public clients such as browser or mobile applications, PKCE is an important part of modern authorization-code deployments.

34. What are OAuth2 scopes?

Scopes represent permissions requested or granted to a client.

For example:

  • order:read
  • order:write
  • profile:read

A resource server can use scopes to determine whether a bearer token has sufficient permission to access an endpoint.

35. What is an Authorization Server?

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.

36. What is a Resource Server?

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.

37. What is an Identity Provider (IdP)?

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.

38. OAuth2 vs OpenID Connect (OIDC)?

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

39. How do you integrate Keycloak with Spring Boot?

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.

40. How do you secure APIs using OAuth2?

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.

Production & Best Practices

41. How do you prevent CSRF attacks?

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.

42. What is CORS and how do you configure it?

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.

43. How do you protect against XSS attacks?

XSS stands for Cross-Site Scripting.

Common defensive practices include:

  • Output encoding
  • Input validation where appropriate
  • Content Security Policy
  • Secure cookie configuration
  • Avoiding unsafe HTML rendering
  • Using framework protections correctly

For APIs, developers should also ensure that untrusted input is handled safely and is not reflected into HTML without proper encoding.

44. How do you implement rate limiting for secure APIs?

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:

  • API Gateway
  • Load balancer
  • Application
  • Distributed cache such as Redis

For microservices, centralized rate limiting at the gateway is often useful, while sensitive operations may also require application-level limits.

45. How do you rotate JWT signing keys?

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.

46. How do you implement Single Sign-On (SSO)?

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.

47. How do you secure communication between microservices?

Internal network access should not automatically be treated as proof of identity.

Depending on the environment, service-to-service security can use:

  • OAuth2 client credentials
  • JWT bearer tokens
  • mTLS
  • Workload identity
  • Network policies
  • API gateways

For highly sensitive systems, authentication, authorization, encryption, identity management, and network controls should work together.

48. How do you debug Spring Security issues?

Start by identifying exactly where the request is failing.

Check:

  • Is the request reaching the application?
  • Is authentication succeeding?
  • Is the SecurityContext populated?
  • Is the token valid?
  • Are the required authorities present?
  • Is the endpoint authorization rule correct?
  • Is method-level authorization rejecting the request?
  • Is CORS or CSRF involved?

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.

49. Describe a production security issue you resolved.

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:

  1. Explain the production symptom.
  2. Describe the business impact.
  3. Explain how you investigated the issue.
  4. Identify the root cause.
  5. Explain the immediate fix.
  6. Explain the permanent solution.
  7. Describe how you prevented the issue from happening again.

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.

50. Design a secure authentication and authorization architecture for a Spring Boot microservices application.

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:

  • OAuth2 scopes
  • Roles
  • Authorities
  • Method-level security
  • Domain-specific authorization policies

A production architecture should also include:

  • HTTPS everywhere
  • Secure key management
  • Signing-key rotation
  • Short-lived access tokens
  • Refresh-token protection
  • Audit logging
  • Rate limiting
  • Security monitoring
  • Secure secrets management
  • Least-privilege access
  • Security testing

Senior Interview Scenario: A JWT Is Valid but the User Gets 403

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:

  • What authorities were extracted from the token?
  • Are scopes mapped with the expected prefix?
  • Does the endpoint require a role or authority?
  • Is there a mismatch between ROLE_ADMIN and ADMIN?
  • Is method-level security rejecting the request?
  • Is a custom JwtAuthenticationConverter changing authority mapping?

This distinction is important:

401 usually indicates an authentication problem.

403 usually indicates that the request was understood but access was not permitted.

Spring Security Interview Cheat Sheet

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

What Senior Interviewers Really Expect

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:

  • Why would you choose OAuth2?
  • When would you use session authentication instead of JWT?
  • How do you revoke compromised tokens?
  • How do you rotate signing keys?
  • How do microservices authenticate with each other?
  • Where should authorization be enforced?
  • How do you handle a compromised access token?
  • How do you prevent excessive privileges?
  • How do you debug a 401 or 403 in production?

The strongest interview answers connect the technology to security, scalability, operational simplicity, and real production scenarios.

Conclusion

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.

Frequently Asked Questions

Is JWT the same as OAuth2?

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.

Is JWT secure?

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.

What is the difference between OAuth2 and OIDC?

OAuth2 focuses on authorization, while OpenID Connect adds an identity and authentication layer on top of OAuth2.

Should every Spring Boot microservice validate JWT tokens?

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.

What is the most important Spring Security concept for senior developers?

Understanding how authentication, authorization, SecurityContext, filters, token validation, and application-level authorization work together is more valuable than memorizing individual configuration properties.

Share Your Interview Question

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

Post a Comment

0 Comments

Close Menu