Skip to main content

Spring Boot Security (Spring Security)

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

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Data Types in C

C Programming: Understanding Data Types Think of your kitchen. You store a large bag of flour in a big bin, a pinch of saffron in a tiny jar, and milk in a liquid measuring jug. You do not put liquids into paper bags, and you do not use a massive bucket for a single teaspoon of sugar. C programming works the exact same way. When you create a variable, you must tell the computer exactly what kind of "container" to build in its memory. We call these containers Data Types . They dictate what kind of data the container holds, how much space it takes up, and what operations you can perform on it. 1. Primitive Data Types C offers several built-in, "primitive" data types. Think of these as the fundamental storage containers. int (Integer): You use this to store whole numbers without decimals. Real-life example: Counting the number of people in a room or tracking a player's score in a video game. char (Character): You use this ...