Spring Security, OAuth2, and JWT are essential topics for modern Java backend and microservices development.
For senior Java interviews, knowing how to configure SecurityFilterChain is only the beginning. Interviewers often go deeper into authentication, authorization, filter chains, JWT validation, OAuth2 flows, access and refresh tokens, roles and authorities, resource servers, authorization servers, and production security troubleshooting.
This guide covers 25 Spring Security, OAuth2, and JWT interview questions and answers, ranging from core concepts to real-world production scenarios.
Spring Security currently provides support for OAuth2 Client, OAuth2 Resource Server, and Authorization Server functionality. A resource server can protect APIs using JWT or opaque bearer tokens.
Client
|
| Login / Access Token
v
Authorization Server
|
| JWT Access Token
v
Spring Boot Resource Server
|
| Validate + Authorize
v
Protected APIs
|
+---- Database
+---- Microservices
+---- External APIsThe authorization server is responsible for issuing tokens, while the resource server protects APIs and validates bearer tokens.
With Spring Boot, a resource server can be configured using an issuer URI. Spring Security can discover the authorization server metadata and public keys and validate JWT claims such as issuer and expiration.
Spring Security is a framework for securing Java applications by providing authentication, authorization, protection against common attacks, and integration with security standards such as OAuth2 and OpenID Connect.
For a web application, incoming HTTP requests pass through Spring Security's security infrastructure before reaching the application controller.
HTTP Request
|
v
Security Filters
|
v
Authentication
|
v
SecurityContext
|
v
Authorization
|
v
ControllerAuthentication establishes who the caller is. Authorization determines whether that authenticated principal is allowed to perform the requested operation.
For senior-level interviews, understand that Spring Security is heavily based on filters, authentication providers, security contexts, and authorization mechanisms rather than simply being a collection of annotations.
Authentication answers:
"Who are you?"
Authorization answers:
"What are you allowed to do?"
For example:
User logs in
|
v
Authentication
|
v
User identity established
|
v
Authorization
|
v
Can this user access /admin?A user can be successfully authenticated but still receive a 403 response because they do not have sufficient authority.
In Spring Security, authentication results in an Authentication object representing the authenticated principal and its authorities.
The authenticated information is associated with the security context for the request.
Authorization then evaluates whether those authorities satisfy the security rules for the requested resource.
Credentials / JWT
|
v
Authentication
|
v
Authentication object
|
v
Authorities
|
v
Authorization decision
|
+---- Allowed
|
+---- DeniedThis distinction is particularly important when troubleshooting 401 versus 403 responses.
Spring Security processes incoming HTTP requests through a chain of security filters.
Different filters perform different responsibilities, such as:
A simplified flow is:
HTTP Request
|
v
Security Filter Chain
|
+--> Authentication
|
+--> Security Context
|
+--> Authorization
|
v
Controller / REST EndpointThe exact filters involved depend on the application's configuration and authentication mechanism.
SecurityFilterChain defines how Spring Security should secure HTTP requests.
A typical Spring Boot configuration can look like:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}For a JWT resource server, the configuration can enable JWT bearer-token processing:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 ->
oauth2.jwt());
return http.build();
}Spring Security's current documentation uses SecurityFilterChain as the primary configuration model for servlet applications.
Both are used for authorization, but they differ in how roles are represented.
hasRole() commonly applies the ROLE_ prefix.
.requestMatchers("/admin/**")
.hasRole("ADMIN")This generally corresponds to an authority such as:
ROLE_ADMINhasAuthority() checks the authority value directly.
.requestMatchers("/reports/**")
.hasAuthority("REPORT_READ")For fine-grained permissions, authorities can be more expressive than broad roles.
| HTTP Basic | JWT Bearer Authentication |
|---|---|
| Credentials are sent with requests | Bearer access token is sent with requests |
| Requires HTTPS for confidentiality | Requires HTTPS for token protection |
| Common for simple/internal scenarios | Common for APIs and distributed systems |
| Server authenticates credentials | Resource server validates the token |
JWT authentication can be useful in distributed systems because resource servers can validate signed tokens without maintaining a traditional server-side session for every request.
JWT stands for JSON Web Token.
A JWT is a compact token format that can carry claims and, when signed, allows the receiver to verify that the token has not been modified.
A simplified flow is:
User authenticates
|
v
Authorization Server
|
v
Signed JWT
|
v
Client
|
| Authorization: Bearer <token>
v
Resource Server
|
v
JWT validation
|
v
AuthorizationA JWT should not be treated as encrypted merely because it is encoded. A signed JWT provides integrity/authenticity properties; sensitive information should not be placed in a token merely because it is base64url encoded.
A JWT normally consists of three Base64URL-encoded parts separated by dots:
HEADER.PAYLOAD.SIGNATUREHeader contains metadata such as the token type and signing algorithm.
Payload contains claims such as issuer, subject, expiration, and scopes.
Signature allows the recipient to verify that the signed content has not been altered.
Header
+
Payload
+
Signature
=
JWTA typical resource-server flow looks like this:
Client
|
| Authorization: Bearer JWT
v
Spring Security
|
v
JWT Decoder
|
+--> Signature validation
+--> Issuer validation
+--> Expiration validation
+--> Other configured validation
|
v
Authentication
|
v
Authorization
|
v
REST ControllerSpring Security's JWT resource-server support validates the bearer token, including its signature and standard claims such as exp, nbf, and iss, according to the configured validation strategy. Scopes can also be mapped to authorities with the SCOPE_ prefix by default.
An access token is used to access protected resources.
A refresh token is used to obtain a new access token when the existing access token expires, when the authorization server supports that flow.
Client
|
+---- Access Token ----> Resource Server
|
+---- Refresh Token ---> Authorization Server
|
v
New Access TokenAccess tokens are generally short-lived compared with refresh tokens.
Refresh tokens require stronger protection because possession of a valid refresh token can allow acquisition of additional access tokens.
The answer depends on the type of client and its threat model.
For browser applications, token storage must be designed carefully to reduce exposure to attacks such as XSS and token theft.
For server-side applications, tokens can generally be kept in protected server-side storage rather than exposing long-lived credentials to the browser.
For browser-based applications, a common approach is to use secure, appropriately configured cookies for sensitive session/refresh-token handling where the architecture supports it.
Important security properties include:
There is no universal "store every JWT in localStorage" rule. Storage should be chosen based on the client architecture and threat model.
OAuth2 is an authorization framework that allows a client to obtain delegated access to protected resources.
A typical authorization-code flow looks like:
Resource Owner
|
v
Client Application
|
v
Authorization Server
|
| Authorization Code
v
Client
|
| Token Request
v
Authorization Server
|
| Access Token
v
Client
|
| Bearer Token
v
Resource ServerOAuth2 separates the responsibilities of the authorization server from the protected resource server.
Spring Security supports OAuth2 client and resource-server functionality, while Spring Authorization Server provides functionality for building an authorization server.
For modern applications, the most important OAuth2 flows to understand are:
Older material may list the password grant and implicit grant, but these are not the flows you should recommend for modern application designs.
Spring Authorization Server's current documentation lists Authorization Code, Client Credentials, Refresh Token, Device Code, and Token Exchange among its supported authorization-grant capabilities.
OAuth2 and JWT solve different problems.
OAuth2 is an authorization framework that defines how clients can obtain and use access tokens.
JWT is a token format.
OAuth2
|
+-- Defines authorization flows
|
+-- Defines client/resource interactions
|
v
Access Token
|
+-- May be a JWT
|
+-- May be an opaque tokenTherefore, OAuth2 does not mean JWT, and JWT does not automatically mean OAuth2.
Spring Security resource servers support both JWT and opaque bearer tokens.
OAuth2 primarily provides an authorization framework.
OpenID Connect (OIDC) builds an identity layer on top of OAuth2 and provides standardized mechanisms for user authentication and identity information.
In a login scenario, OIDC introduces concepts such as the ID Token and UserInfo endpoint.
A useful interview explanation is:
OAuth2
|
+-- Authorization
OpenID Connect
|
+-- OAuth2
|
+-- Authentication / IdentitySpring Security's OAuth2 client support detects OIDC use when the openid scope is requested and uses OIDC-specific components.
An Authorization Server is responsible for issuing tokens after validating the client and authorization request.
It can handle responsibilities such as:
Client
|
v
Authorization Server
|
+---- Access Token
|
+---- Refresh Token
|
+---- ID Token (OIDC)
|
+---- JWK SetSpring Authorization Server provides a framework for building OAuth2 authorization servers and supports OAuth2/OIDC-related capabilities.
A Resource Server is the application that protects APIs and validates access tokens presented by clients.
Client
|
| Bearer Access Token
v
Resource Server
|
+---- Validate token
|
+---- Check authorities
|
v
Protected ResourceFor JWT-based resource servers, Spring Security can decode and validate JWT bearer tokens using the configured issuer and signing keys.
A common configuration is:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com/issuerSpring Security uses the issuer information to discover the authorization server metadata and signing-key information, then validates incoming JWTs.
Depending on configuration, validation includes checking the token signature and claims such as issuer and expiration. Spring Security can also map scopes to authorities using the SCOPE_ prefix by default.
For environments where discovery is not appropriate, a JWK Set URI or an explicit decoder can also be configured according to the application's requirements.
| Session-Based | JWT-Based |
|---|---|
| Authentication state is typically maintained server-side | Access token carries claims and is presented by the client |
| Session ID identifies the server-side session | Bearer token identifies the authorization context |
| Easy server-side invalidation | Revocation requires additional design for self-contained JWTs |
| Often suitable for traditional web applications | Common for distributed APIs and service-to-service architectures |
JWT does not automatically make an application more secure. Token lifetime, key management, storage, validation, revocation strategy, and transport security all matter.
Role-based authorization can be expressed using roles:
.requestMatchers("/admin/**")
.hasRole("ADMIN")Permission-based authorization can use authorities:
.requestMatchers("/orders/**")
.hasAuthority("ORDER_READ")Method-level security can also be used for fine-grained authorization:
@PreAuthorize("hasAuthority('ORDER_READ')")
public Order getOrder(Long id) {
...
}A practical system may use roles for broad business responsibilities and authorities/scopes for more granular permissions.
A typical architecture is:
Client
|
| Bearer Access Token
v
API Gateway
|
v
Spring Boot Resource Server
|
+---- JWT Validation
|
+---- Authorization
|
v
Business ServicesKey security controls include:
The resource server should validate tokens rather than trusting claims simply because they are present in a request.
Access tokens should generally be short-lived.
When an access token expires, a client that has a valid refresh token can request a new access token from the authorization server, assuming the authorization server and grant flow support refresh tokens.
Access Token
|
| expired
v
Client
|
| Refresh Token
v
Authorization Server
|
v
New Access Token
|
v
Resource ServerThe refresh token should be protected more carefully because it can be used to obtain additional access tokens.
Refresh-token rotation, revocation, and reuse detection can be important depending on the authorization server and threat model.
A common architecture is:
Authorization Server
|
| JWT
v
Client -------> API Gateway
|
+---------+---------+
| | |
v v v
Service A Service B Service C
| | |
+---------+---------+
|
Internal APIsEach protected service can act as an OAuth2 resource server and validate access tokens according to the organization's security architecture.
Important considerations include:
For service-to-service communication without a user context, the OAuth2 client-credentials flow is commonly relevant.
This is one of the most important senior-level Spring Security scenarios.
I would first determine whether the problem is authentication or authorization.
Authorization: Bearer <access-token>Confirm that the client is actually sending the expected token.
A 401 Unauthorized response commonly indicates that authentication failed or credentials/token processing did not succeed.
A 403 Forbidden commonly indicates that authentication succeeded but the authenticated principal is not authorized to access the resource.
The exact response behavior depends on the application's security configuration.
Inspect the token's expiration claim and confirm that the client's clock and server clock are reasonably synchronized.
Verify that the JWT's iss claim matches the configured issuer.
Verify that the resource server can obtain the correct JWK set and that the token was signed using a supported key.
Spring Security supports automatic key rotation when new keys are made available through the configured JWK source.
If audience validation is configured, verify that the token contains the expected aud value.
For example, a token may contain:
{
"scope": "orders.read orders.write"
}Spring Security's JWT resource-server support maps scopes to authorities using the SCOPE_ prefix by default.
SCOPE_orders.read
SCOPE_orders.writeTherefore, authorization rules must match the authority representation actually produced by the application.
Verify that public endpoints, authenticated endpoints, and authorization rules are configured as intended.
Look for changes to:
If the API sits behind an API Gateway or load balancer, verify that the Authorization header is not being removed or modified.
Also check whether different environments are using different authorization servers, issuers, audiences, or signing keys.
Senior-level principle: Don't immediately regenerate tokens. First determine whether the failure is caused by token presence, token validation, authority mapping, filter-chain configuration, or downstream infrastructure.
Before a senior Java interview, make sure you can explain:
OAuth2 is an authorization framework. JWT is a token format.
OAuth2 access tokens can be JWTs or opaque tokens. Spring Security resource servers support both approaches.
Understand the ROLE_ convention used with role-based authorization and how direct authorities are evaluated.
Never trust a JWT simply because it is syntactically valid. Signature and relevant claims must be validated.
Token storage should account for XSS, CSRF, token theft, browser architecture, and the sensitivity/lifetime of the token.
They commonly point to different stages of the security process and should be investigated differently.
At senior level, avoid giving only configuration snippets.
Explain the complete request flow.
For example, instead of saying:
"We use JWT for authentication."
A stronger answer is:
"The client sends a bearer access token to the resource server. Spring Security extracts the token, validates its signature and relevant claims, creates an authenticated security context, and then authorization rules determine whether the request has the required authority or scope."
Similarly, instead of saying:
"We use OAuth2."
Explain which component is the client, which component is the authorization server, which APIs are resource servers, which grant flow is being used, and how tokens are validated.
Spring Security, OAuth2, and JWT are not just interview topics. They form the foundation of security for many modern Spring Boot APIs and microservices.
A senior Java developer should understand the complete security flow:
Authentication → Token Issuance → Token Validation → Security Context → Authorization → Protected Resource
You should also understand the differences between:
Most importantly, security should be designed around the application's threat model and business requirements rather than simply adding JWT because it is popular.
A strong senior engineer should be able to explain not only how authentication works, but also what happens when the token expires, a signing key rotates, a scope is missing, an authorization rule changes, or a production deployment suddenly starts returning 401 and 403 responses.
No. JWT is a token format, while OAuth2 is an authorization framework. OAuth2 can use JWT access tokens, but access tokens can also be opaque.
SecurityFilterChain defines the security rules and filters applied to incoming HTTP requests. It is the primary configuration mechanism for servlet-based Spring Security applications.
401 commonly indicates an authentication problem, while 403 commonly indicates that the request was authenticated but the principal does not have sufficient authorization.
A resource server protects APIs and validates access tokens presented by clients.
An authorization server authenticates or integrates with authentication systems, processes authorization requests, and issues tokens according to supported OAuth2/OIDC flows.
Refresh tokens allow a client to obtain new access tokens without requiring the user to repeatedly authenticate, when the authorization server and flow support them.
It can obtain signing keys through the configured authorization-server metadata/JWK configuration, validate the token signature and relevant claims, and convert the validated token into an authenticated security principal.
0 Comments