Spring Security JWT Interview Questions and Answers

Master JWT (JSON Web Token) authentication in Spring Security with interview questions covering JWT structure, token generation, validation, signing algorithms, refresh tokens, stateless authentication, access tokens, and production best practices.


Introduction

Modern REST APIs and Microservices are typically stateless.

Instead of maintaining server-side sessions, applications authenticate users using JWT (JSON Web Token).

JWT has become the industry standard for securing

  • REST APIs
  • Mobile Applications
  • Microservices
  • API Gateway
  • Cloud Applications
  • Single Page Applications (React, Angular, Vue)

Spring Security integrates seamlessly with JWT to provide scalable, stateless authentication.


JWT Authentication Architecture

flowchart LR

User --> LoginAPI

LoginAPI --> AuthenticationManager

AuthenticationManager --> JWTGenerator

JWTGenerator --> JWTToken

JWTToken --> Client

Client --> ProtectedAPI

ProtectedAPI --> JWTFilter

JWTFilter --> SecurityContext

SecurityContext --> Controller

Q1. What is JWT?

Answer

JWT stands for JSON Web Token.

It is a compact, URL-safe token used to securely transmit user identity and claims between two parties.

Instead of storing user sessions on the server,

the server sends a signed JWT to the client.

The client includes the JWT in every request.


Q2. Why do we use JWT?

JWT enables stateless authentication.

Benefits

  • No server-side session storage
  • Scalable for microservices
  • Suitable for REST APIs
  • Easy API Gateway integration
  • Works well with mobile applications
  • Supports distributed systems

JWT is commonly used in cloud-native architectures.


Q3. What is the structure of a JWT?

A JWT consists of three parts.

Header.Payload.Signature

Example

eyJhbGciOiJIUzI1NiJ9.
eyJzdWIiOiJ2ZW51In0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

JWT Structure

flowchart LR

Header --> Payload

Payload --> Signature

Q4. What is contained in the Header?

The header contains metadata about the token.

Example

{
  "alg": "HS256",
  "typ": "JWT"
}

Common fields

  • Algorithm (alg)
  • Token Type (typ)

Q5. What is contained in the Payload?

The payload contains claims.

Example

{
  "sub": "john",
  "roles": ["ROLE_USER"],
  "exp": 1783500000
}

Common claims

  • sub → Subject
  • iss → Issuer
  • aud → Audience
  • iat → Issued At
  • exp → Expiration Time
  • nbf → Not Before
  • jti → Token ID

Never store sensitive information in the payload, because it is Base64URL encoded, not encrypted.


Q6. What is the Signature?

The signature guarantees token integrity.

Signature generation

HMACSHA256(

Header +

Payload +

SecretKey

)

If any part of the token changes,

signature verification fails.


Q7. How does JWT authentication work?

Workflow

  1. User logs in.
  2. Credentials are authenticated.
  3. Server generates JWT.
  4. Client stores JWT.
  5. Client sends JWT in every request.
  6. JWT filter validates token.
  7. Authentication stored in SecurityContextHolder.

JWT Authentication Flow

sequenceDiagram
User->>LoginAPI: Username & Password
LoginAPI->>AuthenticationManager: Authenticate
AuthenticationManager-->>LoginAPI: Success
LoginAPI->>JWTGenerator: Generate Token
JWTGenerator-->>User: JWT
User->>ProtectedAPI: Authorization: Bearer JWT
ProtectedAPI->>JWTFilter: Validate
JWTFilter->>SecurityContextHolder: Store Authentication
SecurityContextHolder-->>Controller: Continue

Q8. Where should JWT be stored?

Recommended

  • HttpOnly Secure Cookies (for browser-based apps)
  • Secure in-memory storage (for native/mobile apps)

Avoid

  • Local Storage (sensitive browser apps)
  • Session Storage for highly sensitive applications

Storage strategy depends on the client type and threat model.


Q9. What are Refresh Tokens?

Access Tokens should have short expiration times.

Refresh Tokens allow obtaining a new Access Token without requiring the user to log in again.

Refresh Token Flow

flowchart LR

AccessTokenExpired --> RefreshToken

RefreshToken --> AuthorizationServer

AuthorizationServer --> NewAccessToken

Common lifetimes

  • Access Token → 15–30 minutes
  • Refresh Token → Days or weeks (based on business requirements)

Q10. JWT Best Practices

Use HTTPS

Never transmit JWT over HTTP.


Keep Access Tokens Short-Lived

Reduce exposure if compromised.


Validate Signature and Expiration

Reject invalid or expired tokens.


Never Store Sensitive Data in JWT

Use claims only for identity and authorization.


Rotate Refresh Tokens

Invalidate old refresh tokens after use.


Banking Example

flowchart TD

Customer --> LoginAPI

LoginAPI --> JWT

JWT --> MobileApp

MobileApp --> PaymentAPI

PaymentAPI --> JwtFilter

JwtFilter --> SecurityContext

SecurityContext --> PaymentController

Every protected request is authenticated using the JWT.


Common Interview Questions

  • What is JWT?
  • Why use JWT?
  • Explain the JWT structure.
  • What is stored in the Header?
  • What is stored in the Payload?
  • What is the Signature?
  • Explain the JWT authentication flow.
  • Where should JWT be stored?
  • What are Refresh Tokens?
  • JWT best practices?

Quick Revision

Topic Summary
JWT Stateless authentication token
Header Algorithm & token type
Payload Claims
Signature Token integrity
Access Token Used for API requests
Refresh Token Generates new access token
Bearer Token Authorization header
JWT Filter Validates tokens
SecurityContextHolder Stores authentication
HTTPS Required for secure transmission

Complete JWT Request Lifecycle

sequenceDiagram
Client->>LoginAPI: Username & Password
LoginAPI->>AuthenticationManager: Authenticate
AuthenticationManager-->>LoginAPI: Success
LoginAPI-->>Client: Access Token + Refresh Token
Client->>ProtectedAPI: Bearer Access Token
ProtectedAPI->>JwtAuthenticationFilter: Validate JWT
JwtAuthenticationFilter->>JwtService: Verify Signature & Expiration
JwtService-->>JwtAuthenticationFilter: Valid
JwtAuthenticationFilter->>SecurityContextHolder: Store Authentication
SecurityContextHolder-->>Controller: Continue Request
Controller-->>Client: Response

Production Example – Banking Payment API

A banking application exposes

POST /api/v1/payments

Workflow

  1. Customer logs in using username and password.

  2. Spring Security authenticates the credentials.

  3. The server generates:

    • Access Token
    • Refresh Token
  4. Mobile application stores the tokens securely.

  5. Every payment request includes:

Authorization: Bearer eyJhbGciOiJIUzI1Ni...
  1. JwtAuthenticationFilter:

    • Extracts the token.
    • Validates the signature.
    • Checks expiration.
    • Loads user details.
  2. Authentication is stored in SecurityContextHolder.

  3. AuthorizationFilter checks the TRANSFER_FUNDS authority.

  4. Payment request reaches the controller.

http
    .addFilterBefore(
        jwtAuthenticationFilter,
        UsernamePasswordAuthenticationFilter.class
    );
flowchart LR

MobileApp --> AuthorizationHeader

AuthorizationHeader --> JwtAuthenticationFilter

JwtAuthenticationFilter --> JwtService

JwtService --> UserDetailsService

UserDetailsService --> SecurityContextHolder

SecurityContextHolder --> AuthorizationFilter

AuthorizationFilter --> PaymentController

PaymentController --> PaymentService

PaymentService --> PostgreSQL

JWT Claims

Claim Meaning
sub Subject (User)
iss Issuer
aud Audience
exp Expiration Time
iat Issued At
nbf Not Before
jti Unique Token Identifier

JWT vs Session Authentication

Feature JWT Session
Server Session
Stateless
Horizontal Scaling Excellent Limited
Mobile Friendly Less suitable
Microservices Excellent Difficult
Token Stored on Client Session ID
Revocation More complex Easier

HS256 vs RS256

Feature HS256 RS256
Algorithm HMAC SHA-256 RSA SHA-256
Keys Shared secret Public/Private key pair
Performance Faster Slightly slower
Microservices Limited Preferred
Third-party verification Not suitable Excellent

JWT Authentication Flow in Microservices

flowchart TD

Client --> ApiGateway["API Gateway"]

ApiGateway["API Gateway"] --> JwtAuthenticationFilter

JwtAuthenticationFilter --> UserService

ApiGateway["API Gateway"] --> PaymentService

ApiGateway["API Gateway"] --> LoanService

JwtAuthenticationFilter --> SecurityContextHolder

The JWT is validated once at the gateway (or by each service, depending on the architecture), and trusted identity information is propagated to downstream services.


Key Takeaways

  • JWT (JSON Web Token) enables stateless authentication by carrying identity and authorization claims inside a signed token.
  • A JWT consists of Header, Payload, and Signature, where the signature protects the token from tampering.
  • The payload contains claims such as the subject, roles, issuer, and expiration time, but should never contain sensitive information.
  • During each request, a JWT authentication filter validates the token, loads user details if necessary, and stores the authenticated user in the SecurityContextHolder.
  • Access Tokens should be short-lived, while Refresh Tokens provide a secure mechanism for obtaining new access tokens without repeated logins.
  • JWT-based authentication is ideal for REST APIs, mobile applications, cloud-native systems, and microservice architectures because it avoids server-side session storage.
  • Always use HTTPS, validate signatures and expiration times, protect refresh tokens, and follow secure client-side storage practices.
  • Understanding JWT authentication is essential for designing secure, scalable, and production-ready Spring Boot applications.