Spring Security Interview Questions 2026: JWT & OAuth2

Spring Security Interview Questions 2026: JWT & OAuth2

Here’s how it usually goes: you’ve spent two weeks grinding LeetCode, you feel solid on collections and streams, and then the interviewer opens with “Walk me through how JWT-based authentication works in Spring Security.” Silence. This is the question that separates candidates who’ve read documentation from candidates who’ve actually built secured APIs — and interviewers at EPAM, product startups, and even TCS service-line projects know the difference immediately.

⏱️ 9 min read | 📚 Updated June 2026

💡 Quick Tip: Need fast answers? Jump directly to the FAQ section below.

View Quick Answers ↓

This guide is for Java developers — freshers to 4-year experienced — preparing for Spring Security rounds in 2026. By the time you finish, you’ll be able to explain authentication vs authorization without fumbling, write a JWT filter from memory, describe OAuth2 flows clearly, and handle follow-up grenades about CSRF and CORS without flinching.

Table of Contents

What Interviewers Are Actually Testing

Spring Security Interview Questions 2026: JWT & OAuth2
Spring Security Interview Questions 2026: JWT & OAuth2 — key points at a glance

Security questions aren’t really about memorizing API names. They’re about whether you understand why something exists. When a TCS architect asks “What’s the difference between authentication and authorization?”, the boring answer is “authentication is who you are, authorization is what you can do.” The answer that gets you hired explains how Spring Security models this: AuthenticationManager handles the first, AccessDecisionManager (or the newer AuthorizationManager in Spring Security 6) handles the second, and they’re deliberately separated so you can swap implementations.

At EPAM and product startups, expect the bar to go higher. They’ll ask you to walk through the SecurityFilterChain request lifecycle, explain why stateless JWT APIs disable session creation, or describe the OAuth2 Authorization Code flow with PKCE. Infosys and Wipro service projects tend to focus more on configuration — can you secure endpoints by role, can you explain why CORS needs to be handled at the security layer, not just at the controller.

Pro tip: If you can draw the Spring Security filter chain on a whiteboard — from ChannelProcessingFilter down to FilterSecurityInterceptor — you’ll stand out in 90% of interviews. Most candidates know the config, not the internals.

How Security Questions Appear Across Rounds

Round Typical Duration Security Topics Asked Difficulty
Technical Phone Screen 30–45 min Authentication vs Authorization, basic JWT concept, HTTPS vs HTTP Low–Medium
Technical Deep-Dive (F2F or Video) 60–90 min JWT filter implementation, OAuth2 flows, CSRF disabling rationale, CORS config Medium–High
System Design / Architecture 45–60 min Securing microservices, token propagation, refresh token strategy, Keycloak/Okta integration High

Core Concepts with Code

Authentication vs Authorization — Get This Rock Solid

Authentication answers “Are you who you claim to be?” Authorization answers “Are you allowed to do this?” Spring Security 6 (used with Spring Boot 3.x and Java 17/21) makes this cleaner than ever. The SecurityFilterChain bean replaces the old WebSecurityConfigurerAdapter, and you configure both concerns declaratively.

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable()) // stateless JWT API — no session, no CSRF needed
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()   // no authentication needed
            .requestMatchers("/api/admin/**").hasRole("ADMIN") // authorization check
            .anyRequest().authenticated()                    // authentication check
        )
        .sessionManagement(session ->
            session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
    return http.build();
}

Notice csrf.disable() here. This is a deliberate choice for stateless REST APIs that use JWT — and interviewers will ask why. CSRF attacks depend on the browser automatically sending session cookies; if your API uses JWT in the Authorization header, browsers don’t attach it automatically, so the attack vector doesn’t apply. Don’t disable CSRF on a traditional server-rendered app with sessions — that’s the classic wrong move.

JWT: Structure, Validation, and the Filter

A JWT has three Base64URL-encoded parts: header (algorithm), payload (claims), and signature. The server signs it with a secret (HMAC-SHA256) or a private key (RS256). On every request, it verifies the signature — no database lookup, which is why it scales well. The catch: you can’t invalidate a JWT before expiry without a blocklist, which reintroduces state.

// JWT authentication filter — runs once per request
@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            chain.doFilter(request, response); // no token, move on
            return;
        }
        String token = authHeader.substring(7);
        String username = jwtService.extractUsername(token); // parse claims

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails user = userDetailsService.loadUserByUsername(username);
            if (jwtService.isTokenValid(token, user)) {
                // set authentication in context so downstream filters know user is authenticated
                UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        chain.doFilter(request, response);
    }
}

The follow-up question interviewers always ask: “What happens if someone steals the JWT?” Your answer should cover short expiry times (15–30 minutes), refresh tokens stored as HttpOnly cookies, and token rotation. For high-security systems, mention a Redis-backed blocklist for logout scenarios.

OAuth2: The Flow That Trips Everyone Up

OAuth2 is an authorization framework, not an authentication protocol — that’s OpenID Connect (OIDC) layered on top of it. The Authorization Code flow with PKCE is the current standard for web and mobile apps. Spring Security’s spring-boot-starter-oauth2-resource-server makes it straightforward to protect your API as a resource server that validates JWTs issued by an authorization server like Keycloak or Okta.

// application.yml — resource server validating JWTs from Keycloak
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://keycloak.example.com/realms/myrealm
          # Spring auto-fetches the JWKS endpoint and validates signatures

With just this config and the resource server starter, Spring Security validates the JWT signature, expiry, and issuer on every request. You don’t write the filter yourself. Interviewers at EPAM love asking: “What’s the difference between an OAuth2 client and a resource server?” Client obtains tokens; resource server validates them. Simple, but many candidates confuse the two.

CORS — Why It Belongs in Security Config

CORS (Cross-Origin Resource Sharing) must be configured at the Spring Security layer, not just with @CrossOrigin on controllers. Why? Because Spring Security filters run before your controller code. If a preflight OPTIONS request hits the security filter and gets a 403 before reaching your controller annotation, the browser blocks the actual request. Fix it globally in your SecurityFilterChain using http.cors() backed by a CorsConfigurationSource bean.

Pro tip: In production, never set allowedOrigins("*") alongside allowCredentials(true) — the browser will reject it. Enumerate your actual frontend origins explicitly.

Common Wrong Answers and How to Fix Them

Mistake 1: “CSRF is not needed for REST APIs” — stated without qualification. This is partially right but sounds naive. The correct answer: CSRF protection is unnecessary only when your API is truly stateless and uses token-based auth via the Authorization header, not cookie-based sessions. If your REST API uses session cookies (common in legacy systems), CSRF is absolutely still needed.

Mistake 2: Storing JWT in localStorage. Candidates from tutorials often say this. localStorage is accessible via JavaScript, making it vulnerable to XSS attacks. The production pattern is: access token in memory (JS variable), refresh token in an HttpOnly, Secure, SameSite=Strict cookie. This limits the blast radius of an XSS exploit.

Mistake 3: Confusing OAuth2 roles. Mixing up the Resource Owner (end user), Client (your app), Authorization Server (Keycloak/Google), and Resource Server (your API) in an explanation is an instant red flag. Draw the four-corner model before your interview and practice explaining each arrow.

Mistake 4: Using WebSecurityConfigurerAdapter in 2026. It was deprecated in Spring Security 5.7 and removed in 6.0. If you write this in a whiteboard exercise with Spring Boot 3.x, the interviewer knows your knowledge is from 2021 tutorials. Use the SecurityFilterChain bean approach shown above.

A Realistic 1-Week Prep Plan

Don’t try to memorize 50 questions. Build understanding through a small project and you’ll answer any variant they throw at you.

  • Day 1–2: Build a Spring Boot 3.x REST API with JWT from scratch — no YouTube tutorial, use the official Spring Security reference docs. Implement register, login, and a protected endpoint.
  • Day 3: Add role-based access control. Create ADMIN and USER roles, protect different endpoints, test with Postman. Understand GrantedAuthority and how roles map to it.
  • Day 4: Integrate OAuth2 resource server with a local Keycloak Docker instance. Issue a token, call your API. Read the OAuth2 Resource Server docs.
  • Day 5: Fix CORS properly in your project. Try breaking it first, then fix it. This hands-on understanding is gold in interviews.
  • Day 6: Read about refresh token rotation, token blocklisting, and the RFC 6749 OAuth2 spec overview. Pair with our deeper guide on advanced Java and framework concepts.
  • Day 7: Mock interview. Say answers out loud. Security concepts sound completely different spoken vs. read — practice bridges that gap. Check our full Java interview questions bank for additional rounds prep.

Frequently Asked Questions

Is Spring Security knowledge expected for freshers at TCS or Infosys?

For freshers, basic concepts — authentication vs authorization, what HTTPS does, a high-level idea of JWT — are fair game. You won’t be expected to write a custom filter from scratch, but knowing why Spring Security exists and how it plugs into Spring Boot will make you stand out against candidates who only know CRUD.

What’s the most common Spring Security question asked at EPAM India?

Based on what I’ve seen and heard, the JWT filter implementation question comes up most often — specifically, “Walk me through how you’d validate a JWT on every request.” They want to see that you know about OncePerRequestFilter, SecurityContextHolder, and the stateless session policy, not just that you’ve used a library.

Should I learn Keycloak or just focus on Spring Security internals?

Learn Spring Security internals first — that knowledge is transferable everywhere. Add Keycloak as a practical layer on top. Being able to say “I’ve configured Spring Boot as an OAuth2 resource server against Keycloak” is a real differentiator for mid-level roles at product companies and EPAM.

Why do we disable CSRF for JWT APIs specifically?

CSRF attacks exploit the browser’s automatic cookie-sending behavior. When your API authenticates via a JWT in the Authorization header, the browser doesn’t attach it automatically to cross-site requests, so the attack can’t succeed. Disabling CSRF is safe here — but document it in your code with a comment explaining why, because future maintainers (and interviewers reviewing your code) will ask.

What’s the difference between OAuth2 and OpenID Connect in one sentence?

OAuth2 is an authorization framework that lets apps get access tokens to call APIs on a user’s behalf; OpenID Connect (OIDC) is an authentication layer built on top of OAuth2 that adds an ID token so the app can verify who the user actually is. In interviews, saying “OAuth2 alone doesn’t tell you who the user is, OIDC does” immediately shows depth.

How do I handle token refresh in a stateless Spring Security setup?

Issue short-lived access tokens (15–30 minutes) and a longer-lived refresh token stored in an HttpOnly cookie. Create a dedicated /auth/refresh endpoint that validates the refresh token (checking a DB or Redis store to support revocation), issues a new access token, and optionally rotates the refresh token. Never store the refresh token in localStorage — the HttpOnly cookie keeps it inaccessible to JavaScript.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *