1. Spring Security Fundamentals
Spring Security is a framework that provides Authentication, Authorization, and protection against common security attacks for Spring applications.
Without Security
Anyone Can Access Application
With Spring Security
Verify User
↓
Check Permissions
↓
Allow Or Deny Access → Return Response
Security Features
Security Architecture & Authentication vs Authorization
Security Architecture
Client → HTTP Request
↓
Security Filter Chain → Authentication → Authorization
↓
Controller → Service → Repository → Database
↓
HTTP Response
Verifies WHO the user is — identity verification. Example: Username + Password → Identity Verified
Determines WHAT an authenticated user can access. Example: ADMIN → Create/Delete User; USER → View/Update Profile
Spring Security Request Flow
Client Request → Security Filter Chain
↓ Not Authenticated
Authentication
↓ Success
Authorization
↓ Permission Granted
Controller → Response
Authentication Failed → 401 Unauthorized. Authenticated but permission denied → 403 Forbidden. Request successful → 200.
2. Security Filter Chain & Core Components
SecurityFilterChain (Spring Security 6)
A chain of security filters that intercepts every HTTP request before it reaches the controller — the main configuration class used to configure Spring Security behavior.
Responsibilities: Define Public URLs, Secure Endpoints, Configure Authentication, Configure Authorization, Register Filters.
Filter Chain Flow
HTTP Request → Security Filters
↓
Authentication → Authorization
↓
Controller → HTTP Response
UserDetails, UserDetailsService, Authentication Object
Represents authenticated user information used by Spring Security — contains Username, Password, Authorities, Account Status, Lock Status, Expiry Information
Loads user information from database, file, LDAP or an external system. Main responsibility: find user by username, return UserDetails
Represents the current authentication request or authenticated user — contains Principal, Credentials, Authorities, Authentication Status
SecurityContext, SecurityContextHolder, Principal & GrantedAuthority
SecurityContext & SecurityContextHolder
SecurityContext → stores the current user's authentication information during request processing.
SecurityContextHolder → provides access to the SecurityContext anywhere in the application; used to retrieve the current logged-in user.
Principal vs GrantedAuthority
Principal → WHO the user is (typically the username or a custom user object)
GrantedAuthority → WHAT the user can do (a permission or role — e.g. ROLE_ADMIN, ROLE_USER, READ_USER, WRITE_USER)
Spring Security Component Flow
Client → SecurityFilterChain
↓
AuthenticationManager → UserDetailsService → Database
↓
UserDetails → Authentication → SecurityContext
↓
Controller
3. Authentication Process & PasswordEncoder
Authentication Flow
Client → Login Request → UsernamePasswordAuthenticationToken
↓
AuthenticationManager → AuthenticationProvider → UserDetailsService → Database
↓
UserDetails → Password Verification
↓
Authentication Success → SecurityContext → Response
PasswordEncoder & Common Encoders
PasswordEncoder
Encrypts passwords before storing, and verifies passwords during login. Purpose: secure password storage, prevent plain text passwords, compare passwords safely.
Common Password Encoders
BCryptPasswordEncoder → Recommended
Pbkdf2PasswordEncoder → PBKDF2 Algorithm
SCryptPasswordEncoder → Memory-Hard Algorithm
NoOpPasswordEncoder → Plain Text (Not Recommended)
Why BCrypt?
Spring's default, recommended password encoder. Features: Salted Hash, Adaptive Algorithm, Slow Hashing, Resistant To Brute Force Attacks.
Same password → different hash every time, because a random salt is added — Password → Hash1 ($2a$...) and Password → Hash2 ($2a$...) are different but both valid.
AuthenticationManager vs AuthenticationProvider
Main component responsible for authenticating users — receives the authentication request, delegates to AuthenticationProvider, returns the authentication result
Component that performs the actual authentication logic — loads the user, verifies the password, creates the Authentication object
Default AuthenticationProvider, used with UserDetailsService and PasswordEncoder. Flow: Load User → Compare Password → Authentication Success
UsernamePasswordAuthenticationToken & Login Failure Reasons
UsernamePasswordAuthenticationToken
Represents the authentication request before login, and the authenticated user after login.
Before: Username, Password, Authenticated = false
After: Principal, Authorities, Authenticated = true
Login Failure Reasons
Wrong Password, Disabled User, Locked Account, Expired Account, User Not Found
4. JWT Fundamentals
JWT (JSON Web Token)
A compact, self-contained, secure token used for Stateless Authentication.
Why JWT?
Without JWT → Server Stores Session → More Memory → Session Replication Needed
↕
With JWT → Client Stores Token → Server Stays Stateless → Better Scalability
JWT Structure
JWT = Header.Payload.Signature (e.g. xxxxx.yyyyy.zzzzz)
Header
Contains Algorithm & Token Type — alg: HS256, typ: JWT
Payload
Contains Claims (user information) — Username, Role, Subject (User ID), Issued Time (iat), Expiration Time (exp)
Signature
Verifies token integrity and prevents tampering — generated using Header + Payload + Secret Key
JWT Flow & Authorization Header
User Login → AuthenticationManager → Credentials Valid
↓
Generate JWT → Return Token → Client Stores Token
↓
Future Requests → Authorization: Bearer <JWT_TOKEN>
↓
JWT Validation → Controller
Access Token vs Refresh Token
Short-lived, used to access protected APIs — short expiry, sent in every request, contains user claims
Long-lived, used to generate a new access token without logging in again — better security, better UX
JWT Generation & Validation
Generation
Authentication Success → Collect User Details
↓
Create Claims → Set Expiration
↓
Sign Token → Return JWT
Validation
Check Signature → Valid?
↓
Check Expiration → Not Expired?
↓
Extract Username → Load User → Authentication Success
5. JWT Filter, OncePerRequestFilter & Stateless Auth
JWT Filter
Custom filter that intercepts every request to validate the JWT. Responsibilities: Read Authorization Header, Extract Token, Validate Token, Load User, Set Authentication.
OncePerRequestFilter
Spring Security base class that ensures a filter executes only once per HTTP request. Why use it: prevent duplicate execution, ideal for JWT validation.
JWT Filter Flow
Incoming Request → Authorization Header → Bearer Token?
↓ Yes
Extract JWT → Validate JWT → Load UserDetails
↓
Create Authentication → SecurityContextHolder
↓
Continue Filter Chain → Controller
Stateful vs Stateless & Token Refresh
Session stored on the server
JWT stored on the client, server stores nothing — each request must contain a valid JWT
Token Refresh Flow
Login → Access Token + Refresh Token
↓
Access Token Expires → Send Refresh Token
↓
Validate → New Access Token → Continue
Full JWT Authentication Flow (Login + Protected API)
POST /login → UsernamePasswordAuthenticationToken → AuthenticationManager → DaoAuthenticationProvider → UserDetailsService
↓
Authentication Success → Generate JWT → Return Token
↓
GET /users (Bearer JWT) → JWT Filter → Validate Token
↓
SecurityContextHolder → Controller → Response
JWT Advantages & Limitations
Advantages
✓Stateless
✓Scalable
✓Faster, No Session Storage
✓Suitable For Microservices
✓Easy API Authentication
Limitations
✗Cannot Easily Revoke
✗Larger Than A Session ID
✗Secret Key Must Be Protected
✗Short Expiry Recommended
6. Authorization & Role-Based Access Control (RBAC)
RBAC
Restricts application access based on user roles.
ADMIN → Manage Users, Create Reports
TRAINER → Manage Courses, Manage Exams
STUDENT → View Courses, Take Exams
Authorization Flow
Client Request → JWT Validated → Authentication
↓
Extract Roles → Authorization
↓ Granted
Controller → Response
↓ Denied
403 Forbidden
Role vs Authority, Role Hierarchy, hasRole() vs hasAuthority()
High-level access, e.g. ROLE_ADMIN. Role hierarchy: ROLE_ADMIN → ROLE_TRAINER → ROLE_STUDENT (higher roles can inherit lower role permissions)
Specific / fine-grained permission, e.g. DELETE_USER, READ_USER, WRITE_USER
Checks role, automatically adds the ROLE_ prefix
Checks the exact authority, no prefix added
URL-Level Security example: /admin/** → ROLE_ADMIN, /student/** → ROLE_STUDENT.
7. Method Security
Method Security Flow
Request → Authentication → Authorization
↓
@PreAuthorize
↓
Method Executes → Response
Protects individual Service or Controller methods using annotations. @EnableMethodSecurity enables method-level authorization checks.
@PreAuthorize vs @PostAuthorize vs @Secured vs @RolesAllowed
| Annotation | Behavior |
| @PreAuthorize ⭐ | Checks permission before method executes — most flexible; supports role checks, authority checks, custom SpEL expressions |
| @PostAuthorize | Checks permission after method executes — used for validating the returned object / ownership verification |
| @Secured | Restricts a method using roles only — simple |
| @RolesAllowed | JSR-250 standard annotation for role-based access |
8. SecurityContextHolder Usage, CSRF & CORS
Current User Flow
JWT Filter → Authentication
↓
SecurityContextHolder → Service Layer
↓
Current User Available
SecurityContextHolder — Common Uses
Current Username, Current Roles, Audit Logging, Ownership Validation
CSRF vs CORS
An attack where a malicious site sends unauthorized requests using the victim's session. Applies to session-based auth (enable protection); usually disabled for stateless JWT APIs (no server session).
Allows a browser to access resources from another origin — e.g. frontend on localhost:5173 calling backend on localhost:8080. Headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers.
CSRF protects against forged requests; CORS allows legitimate cross-origin browser requests. They solve different problems and are configured independently.
9. OAuth2 & OpenID Connect
OAuth2
An authorization framework that allows applications to access protected resources on behalf of a user, without sharing passwords.
Why OAuth2?
Without → User Shares Password With Every App → Security Risk
↕
With → User Grants Permission → App Gets Access Token → No Password Shared
OAuth2 Roles & Authorization Code Flow
OAuth2 Roles
Resource Owner → User
Client → Application
Authorization Server → Issues Access Tokens
Resource Server → Protected API
Authorization Code Flow
User → Client App → Authorization Server → Login
↓
Authorization Code → Client → Exchange Code
↓
Access Token → Resource Server → Protected Resource
OpenID Connect (OIDC) & OAuth2 vs OIDC
OIDC
An identity layer built on top of OAuth2 — provides Authentication + User Identity.
Token types: Access Token (API Access), ID Token (User Identity), Refresh Token (Renew Access Token)
Authentication + Authorization
JWT vs Session
Stateless, stored on client, scalable — preferred for REST APIs
Stateful, stored on server, simpler — for traditional web apps
Common Security Headers
X-Content-Type-Options → Prevent MIME Sniffing
X-Frame-Options → Prevent Clickjacking
Content-Security-Policy → Restrict Script Sources
Strict-Transport-Security → Force HTTPS
HTTPS & Password Policy
HTTPS encrypts communication between client and server — Confidentiality, Integrity, Authentication.
Password Policy: Minimum 8–12 characters, uppercase, lowercase, number, special character, password expiry (if required), prevent password reuse.
Token Storage Comparison
| Storage | Characteristics |
| HttpOnly Secure Cookie ⭐ | Recommended for browser apps — more secure, not accessible by JavaScript |
| Memory | Common for SPAs — lost on refresh, less persistent |
| Local Storage | Convenient, persistent — but higher XSS risk |
11. Refresh Token Strategy, Rotation & Logout
Refresh Token Strategy
Login → Access Token + Refresh Token
↓
Access Token Expires → Refresh Token Validated
↓
New Access Token → Continue
Refresh Token Rotation
Issue a new refresh token whenever one is used. Benefits: reduce token theft risk, detect reuse, better security.
Logout: JWT → client deletes the token. Refresh Token → invalidate or remove from storage. Future requests → 401 Unauthorized.
12. Common Security Attacks & Mitigation
| Attack | Mitigation |
| XSS (Cross-Site Scripting) | Escape output, Content Security Policy |
| CSRF (Cross-Site Request Forgery) | Enable CSRF protection for session-based apps |
| SQL Injection | Parameterized queries, JPA, Prepared Statements |
| Brute Force (repeated login attempts) | Rate limiting, account lockout, monitoring |
13. Production Security Flow & Checklist
Production Security Flow
Client → HTTPS → SecurityFilterChain
↓
JWT Validation → Authorization
↓
Business Logic → Database
↓
Response
✓Use HTTPS Everywhere
✓Use BCrypt For Passwords
✓Keep JWT Short-Lived
✓Use Refresh Token Rotation
✓Store Tokens Securely
✓Validate JWT On Every Request
✓Use Least Privilege Access
✓Enable Security Headers
✓Restrict CORS Origins
✓Disable CSRF Only For Stateless JWT APIs
✓Log Authentication/Authorization Failures
✓Rotate Secrets And Keys
✓Keep Dependencies Updated
✓Perform Regular Security Audits
14. Top Interview Differences
Authentication vs Authorization
AuthenticationManager vs AuthenticationProvider
Principal vs GrantedAuthority
Role vs Authority
hasRole() vs hasAuthority()
@PreAuthorize vs @PostAuthorize
@Secured vs @RolesAllowed
Access Token vs Refresh Token
JWT vs Session
Stateful vs Stateless
CSRF vs CORS
OAuth2 vs OpenID Connect
BCrypt vs NoOpPasswordEncoder
401 vs 403
HttpOnly Cookie vs Local Storage
15. Real Project Scenarios
CertifyHub Login→AuthenticationManager → DaoAuthenticationProvider → UserDetailsService → PostgreSQL → BCrypt Compare → Generate JWT
Admin / Student Login→ROLE_ADMIN / ROLE_STUDENT → JWT Returned
Every API→Authorization Header → JWT Filter → Validate JWT → Load User → Access Granted
Expired Access Token→Client sends Refresh Token → receive new Access Token
Microservices→JWT passed between services → no shared session required
Course Service→@PreAuthorize → ROLE_TRAINER only
Audit Service→SecurityContextHolder → Current Username → Audit Entry
React Frontend (localhost:5173)→Spring Boot → Enable CORS
JWT Authentication→CSRF Disabled → Stateless API
Google Login→OAuth2 → OIDC → User Profile → JWT Generated
Admin APIs→ROLE_ADMIN → Method Security → Audit Logging
16. Interview One-Liner Revision
›Spring Security → Security Framework
›Authentication → Verify Identity
›Authorization → Verify Permission
›SecurityFilterChain → Security Configuration
›UserDetails → User Information
›UserDetailsService → Load User
›SecurityContext → Current Authentication
›SecurityContextHolder → Access SecurityContext
›Principal → Logged-In User
›GrantedAuthority → Permission Or Role
›PasswordEncoder → Password Hashing
›BCrypt → Salted Password Hash
›AuthenticationManager → Authentication Coordinator
›AuthenticationProvider → Credential Verification
›DaoAuthenticationProvider → Database Authentication
›UsernamePasswordAuthenticationToken → Authentication Object
›JWT → Stateless Authentication Token
›Header → Algorithm Info
›Payload → User Claims
›Signature → Integrity Verification
›Bearer Token → Authorization Header Token
›JWT Filter → Validate Token
›OncePerRequestFilter → Executes Once Per Request
›Access Token → API Access
›Refresh Token → Renew Access Token
›Stateless → No Server Session
›RBAC → Role-Based Access Control
›Role → High-Level Permission
›Authority → Fine-Grained Permission
›hasRole() → Check Role
›hasAuthority() → Check Permission
›@EnableMethodSecurity → Enable Method Security
›@PreAuthorize → Before Execution
›@PostAuthorize → After Execution
›CSRF → Forged Request Protection
›CORS → Cross-Origin Access
›OAuth2 → Authorization Framework
›OIDC → Identity Layer
›ID Token → User Identity
›HTTPS → Encrypted Communication
›Security Headers → Browser Protection
›Refresh Token Rotation → Issue New Refresh Token
›Least Privilege → Minimum Required Access
›401 → Unauthorized
›403 → Forbidden
17. 15-Minute Final Revision Flow
Spring Security → Authentication → Authorization → SecurityFilterChain
↓
UserDetails → UserDetailsService → PasswordEncoder → BCrypt
↓
AuthenticationManager → AuthenticationProvider
↓
JWT → Header → Payload → Signature → JWT Filter → OncePerRequestFilter → SecurityContextHolder
↓
RBAC → Method Security → CSRF → CORS
↓
OAuth2 → OpenID Connect → HTTPS → Refresh Token
↓
Production Security
5–7 Years Interview Mantra — Interviewers Expect You To Explain
✓ Why, not just What — Authentication vs Authorization, JWT vs Session, OAuth2 vs OIDC
✓ Full request lifecycle through SecurityFilterChain, JWT Filter, and SecurityContextHolder
✓ Real production security decisions — token storage, refresh token rotation, CORS restriction
✓ RBAC and method security design for real endpoints (roles vs fine-grained authorities)
✓ Attack mitigation you've actually implemented — CSRF, XSS, SQL Injection, Brute Force
✓ Trade-offs between approaches, backed by real project examples