Spring Security Basics – A Practical Guide for Java Developers

Spring Security Basics – A Practical Guide for Java Developers

By Ganesh, Java Architect with 25+ years of hands-on experience

Security is not an option — it's a must-have for every modern application. Whether you’re building a login page or securing REST APIs, Spring Security gives you a powerful and customizable security framework. But for junior developers, it can feel overwhelming at first.

In this post, I’ll walk you through the absolute basics of Spring Security — what it is, why it matters, and how to get started with real code examples. Let’s make it practical, not theoretical.


🚀 What Is Spring Security?

Spring Security is a framework that handles:

  • Authentication (Who are you?)
  • Authorization (What are you allowed to do?)
  • Protection against common attacks (CSRF, CORS, XSS, etc.)

It integrates deeply with Spring Boot and can secure web pages, REST APIs, or even method calls in your Java code.


🔒 Basic Concepts You Should Know

Concept Description
Authentication Verifying identity (e.g., login with username & password)
Authorization Granting access to specific URLs or actions
Security Filter Chain Chain of filters that apply security rules to every request
UserDetailsService Loads user data (username, roles) from memory or database
PasswordEncoder Encrypts passwords (like BCrypt)

🛠️ Let’s Build a Basic Secure Spring Boot App

Step 1: Add Spring Security Dependency

Use start.spring.io or add this to pom.xml:

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

— You’ll see a default login page!

Spring Security automatically secures everything under / and expects you to log in with:

Username: user
Password: (printed in console)

👨‍💻 Step 3: Configure In-Memory Users

Create a class SecurityConfig.java:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/admin/**").hasRole("ADMIN")
        .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
        .anyRequest().authenticated()
      )
      .formLogin(Customizer.withDefaults());

    return http.build();
  }

  @Bean
  public InMemoryUserDetailsManager userDetailsService() {
    UserDetails user = User.withUsername("john")
        .password(passwordEncoder().encode("password123"))
        .roles("USER")
        .build();

    UserDetails admin = User.withUsername("admin")
        .password(passwordEncoder().encode("adminpass"))
        .roles("ADMIN")
        .build();

    return new InMemoryUserDetailsManager(user, admin);
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

Try accessing:

  • /admin/home → only ADMIN can access
  • /user/home → both USER and ADMIN

✅ Step 4: Add Controller to Test

@RestController
public class DemoController {

  @GetMapping("/user/home")
  public String userHome() {
    return "Welcome USER!";
  }

  @GetMapping("/admin/home")
  public String adminHome() {
    return "Welcome ADMIN!";
  }

  @GetMapping("/")
  public String index() {
    return "Hello! You’re authenticated.";
  }
}

Start the app and try logging in with:

  • 👤 User: john / password123
  • 👤 Admin: admin / adminpass
---

🎯 Summary

In this post, we covered the very basics of Spring Security:

  • What it is and why it matters
  • How to secure endpoints with roles
  • How to configure users in memory

As a junior developer, you don’t need to know everything right away — but building small secured apps like this will give you real confidence.

---

🔗 What’s Next?

  • 🔐 Learn about JWT and token-based security
  • 🔄 Add logout, session management
  • 🔑 Integrate with a database (JPA + MySQL)
  • 🛡️ Learn about CSRF, CORS and custom filters

Stay tuned — I’ll cover these in upcoming blogs.

---

Ganesh, Java Architect Founder – CodeDrivenArchitect.com

Comments

Popular posts from this blog

CodeForge Full-Stack Guide with AI: Spring Boot, React, AWS using ChatGPT-5, Amazon Q & GitHub Copilot