Skip to main content

Command Palette

Search for a command to run...

Spring Security Complete Guide

Published
5 min read
A

Hi there! I'm Azam Pasha, a Computer Science graduate passionate about building things with technology. My journey into the world of programming started with Java, and I'm currently expanding my skills in the full-stack and DevOps space.

From Zero to Hero (No Coding Experience Needed)

Master Spring Security in 30 minutes – Secure your apps like Netflix & Amazon! Real-world stories, simple diagrams, copy-paste code. Beginners to Experts welcome.

🚨 Imagine This: Your app has 10,000 users. A hacker steals all passwords in 5 minutes. Your business? Gone. Spring Security stops this – automatically.

Why Spring Security Saves Companies Millions

Meet Raj, a coffee shop owner building an online ordering app. Customers login, place orders, pay online.

One day, a hacker logs in as "RajAdmin" and deletes everything.

Real-world problem: 95% of apps get hacked because login/password systems fail.

Spring Security = Your digital bodyguard.

Where you see it daily:

  • Netflix login screen

  • Amazon "Add to cart" security

  • Banking apps (HDFC, SBI)

  • Gmail 2FA

Think airport security

Spring Security = metal detectors + guards + cameras. Hackers get caught before entering.

Official Spring Security Documentation – Always check here for latest updates.

Chapter 1: What is Spring Security?

Story: Raj adds Spring Security. Hackers see "Access Denied!" Customers safe. Business grows 10x.

Simple definition: Spring Security = Automatic lock + key system for Java apps.

Jargon Buster:

  • Java = Programming language (like English for computers)

  • Authentication = "Who are you?" (login)

  • Authorization = "What can you do?" (permissions)

Why learn:

  • Jobs pay ₹15L+

  • Every Spring Boot app needs it

  • Zero config = running in 5 mins

Chapter 2: The Magic Filter Chain ( How It Works Inside )

Story: Like airport X-ray → metal detector → passport check. Spring Security has 15 "checkpoints."

Jargon Buster:

  • Filter Chain = Security assembly line (15 steps)

  • Security Context = Memory of "who's logged in"

Real-world: Swiggy login = 15 invisible checks in 0.1 seconds.

Request --> Filter1 --> Filter2 --> ... --> Filter15 --> Your App Code

Memory Hook: "Filters = Checkpoints. Fail any = Stop!"

Chapter 3: 5-Minute Setup (Your First Secure App)

Zero experience? Copy-paste:

<!-- pom.xml - Add this dependency -->

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

This dependency enables authentication, authorization, login pages, filters, and password security automatically in a Spring Boot application

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin();   // enables default login page

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {

        UserDetails user = User.builder()
            .username("raj")
            .password("{noop}password") // plain password (demo only)
            .roles("USER")
            .build();

        return new InMemoryUserDetailsManager(user);
    }
}

Run → http://localhost:8080 → raj/password → DONE!

Exercise: Change password to "coffee123"

Spring Initializr – Generate your project instantly

Chapter 4: Users + Passwords (BCrypt Magic)

Jargon Buster:

  • UserDetailsService = "User database lookup"

  • PasswordEncoder = Password protector

Story: Raj's rival guesses "password123". BCrypt = uncrackable.

java@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();  // Industry standard
}

Password Journey:

text"coffee123"  →  BCrypt Mixer  →  $2a$10$N9qo8uLOickgx2ZMRZoMye...  →  Database

Login → Hash Matched? → YES!

Why BCrypt? 1000 years to crack one password.

Chapter 5 : Roles & Permissions ( Admin vs User )

Jargon Buster:

  • ROLE_USER = Basic access

  • hasRole() vs hasAuthority() = Role check methods

Real-world: Swiggy delivery sees orders, admin sees analytics.

java.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasRole("USER")
.requestMatchers("/public/**").permitAll()

Role Tree:

Chapter 6 : 3 Login Types ( Pick Your Weapon )

Login TypeBest ForReal ExampleCode
Form LoginWeb appsFacebook⭐ Easy
Basic AuthAPIsPostman⭐ Simplest
JWT TokenMobile/SPAInstagram API⭐⭐⭐ Pro

JWT Story: Login once → token works 7 days → no passwords.

JWT generates token like: eyJhbGciOiJIUzI1NiJ9...

Chapter 7 : Lock URLs + APIs

Jargon Buster:

  • antMatchers = URL pattern matcher

  • permitAll() = No login needed

java.authorizeHttpRequests(authz -> authz
    .requestMatchers("/public/**").permitAll()    // Marketing
    .requestMatchers("/coffee/**").hasRole("USER") // Orders
    .requestMatchers("/admin/**").hasRole("ADMIN") // Dashboard
    .anyRequest().authenticated()
)

⚠️ Order matters! Public paths FIRST.

Chapter 8 : Pro Features ( Real-World Must-Haves )

FeatureProblem SolvedReal Example
CSRFFake link attacksForm hijacking
OAuth2"Login with Google"Social login
Remember-MeAuto-login"Keep me signed in"

CSRF Story: Hacker tricks Raj's wife → fake order form → CSRF blocks it.

javahttp.csrf(csrf -> csrf.disable()); // For APIs only!

Spring Security OAuth2 Guide

Final Project: Secure Coffee Shop App (30 Minutes)

What you build:

  1. Login screen

  2. User order history

  3. Admin dashboard

  4. JWT API endpoints

🎉 Result: Hacker-proof coffee shop! 
Raj's business thrives.

GitHub Starter: Create from Spring Initializr

You've Mastered Spring Security! ( Jargon Glossary )

WordSimple Meaning
Filter Chain15 security checkpoints
AuthenticationLogin check
AuthorizationPermission check
BCryptPassword protector
JWTMagic login token
CSRFFake form blocker

You now understand 100% of Spring Security jargon!

✍️ Written by Azam Pasha
Computer Science & Engineering Graduate
🔗 LinkedIn
💻 GitHub
🐦 Twitter