If you’ve ever tried to learn Spring Security, you probably felt like you were fighting a dragon made of XML, filters, and cryptic annotations.
But not today.
Today, we’ll learn Spring Security in the simplest possible way, by building a real-world style app and understanding every piece step-by-step.
🏗️ What We’re Building
Let’s imagine we’re creating a simple Student Management App for a school.
- Teachers can view and add students.
- Admins can delete any student.
- Guests can’t do anything.
We’ll use Spring Boot + Spring Security to:
- Add authentication (login system)
- Add role-based authorization (who can do what)
- Understand the
@EnableWebSecurity
annotation
🧩 Step 1: Add Spring Security Dependency
If you’re using Maven, just add this to your pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
✅ That’s it. The moment you add this, Spring Boot automatically secures your whole app.
Try running your app now — every endpoint will ask for a username and password (default ones generated by Spring Boot).
🧠 Step 2: What Is @EnableWebSecurity
?
This annotation is like saying:
“Hey Spring, I want to control how my web security works — not just use your default rules.”
It activates Spring Security’s custom configuration for web-based security.
So, we’ll create a custom class like this:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.httpBasic(withDefaults());
return http.build();
}
}
Let’s break it down in plain English 👇
-
@EnableWebSecurity
: Tells Spring “I’ll handle web security myself.” -
authorizeHttpRequests
: Defines which endpoints need login. -
formLogin()
: Shows a login form. -
httpBasic()
: Allows basic browser login (useful for APIs).
So right now, every endpoint requires login — but we haven’t said who can log in or what roles they have yet.
🔑 Step 3: Add Authentication (Who Are You?)
Authentication = Proving your identity.
Let’s create a few in-memory users for simplicity.
Add this inside the same SecurityConfig
class:
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.context.annotation.Bean;
@Bean
public UserDetailsService userDetailsService() {
UserDetails teacher = User.withUsername("teacher")
.password("{noop}teacher123") // {noop} = No password encoding for simplicity
.roles("TEACHER")
.build();
UserDetails admin = User.withUsername("admin")
.password("{noop}admin123")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(teacher, admin);
}
🧾 What’s happening:
-
We created two users:
- teacher / teacher123
- admin / admin123
{noop}
tells Spring don’t encrypt the password (only for testing)roles("TEACHER")
androles("ADMIN")
are like badges — we’ll use them soon for authorization.
Now we have authentication — users can log in.
🔒 Step 4: Add Role-Based Authorization (Who Can Do What?)
Now, we’ll secure our endpoints.
Imagine we have this simple StudentController
:
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
@GetMapping
public List<String> getAllStudents() {
return List.of("Alice", "Bob", "Charlie");
}
@PostMapping
public String addStudent(@RequestBody String name) {
return "Student " + name + " added!";
}
@DeleteMapping("/{name}")
public String deleteStudent(@PathVariable String name) {
return "Student " + name + " deleted!";
}
}
Now let’s apply roles in our SecurityConfig
:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/students").hasAnyRole("TEACHER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/students").hasRole("TEACHER")
.requestMatchers(HttpMethod.DELETE, "/students/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.httpBasic(withDefaults());
return http.build();
}
🧩 Explanation:
-
GET /students
→ Teachers and Admins can access. -
POST /students
→ Only Teachers can add. -
DELETE /students/{name}
→ Only Admins can delete.
🧪 Step 5: Test It Out!
Run your app and try these in your browser or Postman:
Action | Endpoint | Role Required | Username |
---|---|---|---|
View all students | GET /students |
TEACHER or ADMIN | teacher/admin |
Add a student | POST /students |
TEACHER | teacher |
Delete a student | DELETE /students/Bob |
ADMIN | admin |
You’ll see:
- Teacher can add, but not delete.
- Admin can delete, but not add.
- Guests can’t do anything.
Boom 💥 — you just built authentication + role-based authorization using Spring Security.
⚙️ Bonus Tip: Common Mistakes Beginners Make
-
Forgetting
{noop}
in passwords → causes “There is no PasswordEncoder mapped for the id” error. -
Using wrong role names → remember Spring adds
ROLE_
prefix internally. -
Not enabling
@EnableWebSecurity
→ your custom security won’t apply.
🏁 Final Thoughts
Spring Security might look scary at first, but once you understand the “why” behind each step:
-
@EnableWebSecurity
→ turn on your own security setup - Authentication → who you are
- Authorization → what you can do
…it becomes one of the most powerful (and safest) parts of your Spring Boot app.
🧰 Complete Example Folder Structure
src/
├─ main/java/com/example/securitydemo/
│ ├─ SecurityConfig.java
│ └─ StudentController.java
└─ resources/
└─ application.properties
✅ You can expand this later with JWT, database users, or OAuth — but now you understand the core foundation.
🌟 Closing Note
If you ever feel lost while learning Spring Security, remember this:
“Don’t learn it to remember every config. Learn it to understand why we secure things.”
That mindset turns you from a copy-paste developer into a real engineer.
Follow me on : Github Linkedin Threads Youtube Channel
Top comments (0)