Spring Boot Security Basics: Complete Deep Dive
Security is one of the most important topics for any Spring Boot developer. Almost every enterprise application requires Authentication, Authorization, Password Encryption, JWT Integration, Role-Based Access Control (RBAC), and strict API Security.
Many developers know how to copy-paste Spring Security configurations, but they completely fail to explain the internal working during interviews. This guide focuses on the absolute core mechanics of how Spring Security intercepts, authenticates, and authorizes incoming requests.
1. Why Do We Need Spring Security?
Imagine an Employee Management System. Without a security layer, your application is an open door:
The Security Guarantee
Implementing Spring Security ensures that:
- Only authenticated users can access restricted APIs.
- Only authorized users (with the correct roles) can perform specific actions.
- Passwords are cryptographically encrypted.
- Tokens (like JWT) are strictly validated on every request.
2. What is Spring Security?
Definition
Spring Security is a comprehensive framework that provides Authentication, Authorization, Session Management, CSRF Protection, and Security Filters for Spring-based applications.
To enable it, you simply add the starter dependency:
What Happens After Adding Spring Security?
The moment you run your application, GET /employees suddenly returns 401 Unauthorized. Why? Because Spring Security aggressively Auto-Configures a default lockdown, securing all endpoints, generating a default user, and printing a randomized password to your console.
3. Architecture & Internal Startup Flow
Startup Sequence
High-Level Request Architecture
4. The SecurityFilterChain
The most important concept in Spring Security is the Filter Chain. The SecurityFilterChain is a sequence of servlet filters that process every incoming HTTP request before it is allowed to reach your @Controller.
Think of it like airport security:
Modern Configuration (Spring Security 6+)
Prior to Spring Security 5.7, developers extended WebSecurityConfigurerAdapter. This is now deprecated. The modern approach uses a @Bean definition:
Internal Working & Important Filters
When a request like GET /employees arrives, it traverses:
Important internal filters interviewers ask about:
SecurityContextHolderFilterUsernamePasswordAuthenticationFilterBasicAuthenticationFilterExceptionTranslationFilterAuthorizationFilter
5. Authentication vs Authorization (Interview Favorite)
| Feature | Authentication | Authorization |
|---|---|---|
| Core Question | Who are you? | What are you allowed to do? |
| Example | Username: madhu | Password: 123456 | Role: ROLE_ADMIN |
| Action | System verifies identity matching the database. | System verifies if the User can Create/Delete/View based on roles. |
6. The Authentication Flow & Internal Classes
This is a definitive interview topic. When a user submits a login request (e.g., {"username":"madhu", "password":"123"}), this is the exact flow:
Crucial Internal Classes to Memorize
UserDetails: Represents the authenticated user (contains Username, Password, Roles, Authorities).UserDetailsService: Contains the logic to load the user from your database vialoadUserByUsername(String username).AuthenticationManager: Responsible for executing the authentication verification process.SecurityContextHolder: Globally stores the logged-in user information for the duration of the request.
7. Password Encoding & BCrypt
You must never store passwords in plain text. If a database is breached, all user accounts are immediately compromised. Passwords must be encrypted.
Why BCryptPasswordEncoder?
- One-way hashing: It cannot be decrypted backward.
- Salt generation: It automatically adds random data to the hash, ensuring identical passwords yield different database hashes.
- Industry standard: Highly resilient to rainbow table attacks.
8. JWT Integration Basics
JWT (JSON Web Token) is used for Stateless Authentication. Instead of the server keeping a session in memory, the user's identity is securely signed and handed to the client as a token.
Traditional Session vs JWT
| Traditional Session Authentication | JWT Authentication |
|---|---|
| Login → Server Creates Session → Stores in RAM → Returns Session ID | Login → Server Generates JWT → Returns Token → Server Stores Nothing |
| Consumes heavy server memory. Difficult to scale across multiple servers. | Stateless. Highly scalable. Client sends Token in Authorization header on every request. |
JWT Structure
Format: Header.Payload.Signature (e.g., xxxxx.yyyyy.zzzzz)
JWT Validation Flow
9. Complete Security Backend Flow
This is the ultimate master blueprint of Spring Security operating with JWTs:
10. Interview Questions Summary
Top Technical Q&A
Q1: What is Spring Security?
A: A framework providing robust authentication, authorization, password encryption, session management, and API security for Spring applications.
Q2: What is the SecurityFilterChain?
A: A collection of security servlet filters that intercept every incoming HTTP request to perform authentication and authorization checks before the request is allowed to reach the application's controllers.
Q3: Why use BCryptPasswordEncoder?
A: Because it utilizes one-way hashing and automatic salt generation, preventing rainbow table attacks and ensuring that a database breach does not expose plain text passwords.
Q4: What is JWT?
A: JSON Web Token is a stateless authentication mechanism where cryptographic proof of identity is stored inside a signed token on the client side, eliminating the need for server-side session memory.
Internal Classes Every 3+ Year Developer Should Know:
SecurityFilterChain, FilterChainProxy, DelegatingFilterProxy, AuthenticationManager, AuthenticationProvider, UserDetails, UserDetailsService, SecurityContextHolder, PasswordEncoder, BCryptPasswordEncoder, UsernamePasswordAuthenticationFilter, OncePerRequestFilter
Thanks for reading Learn Here Fun Pedia
Comments
Post a Comment