Spring Boot Security (Spring Security)

Author Avatar
Learn Here Fun Pedia
5 min read •

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:

GET /employees -> Anyone can leak employee information. POST /employees -> Anyone can create unauthorized records. DELETE /employees/101 -> Anyone can destroy database entries.

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:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </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

Application Start | Create Security Beans | Register Security Filters | Secure Every Request

High-Level Request Architecture

Client | HTTP Request | [ Security Filters ] | [ Authentication ] | [ Authorization ] | Controller | Response

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:

Passenger -> Security Check -> Verification -> Boarding ... ... ... ... Request -> Filter Chain -> Authentication -> Controller

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:

@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() ) .formLogin(); return http.build(); } }

Internal Working & Important Filters

When a request like GET /employees arrives, it traverses:

DispatcherServlet | DelegatingFilterProxy | FilterChainProxy | SecurityFilterChain | Authentication Filter -> Authorization Filter -> Controller

Important internal filters interviewers ask about:

  • SecurityContextHolderFilter
  • UsernamePasswordAuthenticationFilter
  • BasicAuthenticationFilter
  • ExceptionTranslationFilter
  • AuthorizationFilter

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:

Client -> Username/Password | [ UsernamePasswordAuthenticationFilter ] | [ AuthenticationManager ] | [ AuthenticationProvider ] | [ UserDetailsService ] -> loadUserByUsername() | Database | Password Match (BCrypt Check) | Authentication Success -> Stored in SecurityContextHolder

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 via loadUserByUsername(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.
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Encoding: String encoded = passwordEncoder.encode("123456"); // Result: $2a$10$8dfkjsdfksdf... // Verification: boolean isMatch = passwordEncoder.matches("123456", encodedPassword);

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

Request | [ JwtAuthenticationFilter ] (Custom Filter) | Extract Token from "Authorization: Bearer ..." Header | Validate Cryptographic Signature & Expiry | Load User Details | Set Authentication in SecurityContextHolder | Controller Execution

9. Complete Security Backend Flow

This is the ultimate master blueprint of Spring Security operating with JWTs:

Client Request | SecurityFilterChain | Authentication Filter | AuthenticationManager -> UserDetailsService -> Database | PasswordEncoder Match (BCrypt) | Authentication Success | JWT Generated & Client Stores Token | [ NEXT REQUEST ] | JWT Filter Intercepts Request | Token Signature Validation | SecurityContextHolder Populated | Authorization Check (Roles verified) | Controller Executes | Response Returned

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 (0)