# How to Set Up Spring Security in Spring Boot 3.x

## **1️⃣ Introduction**

Security is a **critical aspect** of modern applications, ensuring that **only authorized users can access protected resources**. With the latest updates in **Spring Boot 3.x**, **Spring Security** has introduced **a more streamlined, flexible configuration** using **SecurityFilterChain** and **the new Lambda-based approach**.

In this guide, we will explore **how Spring Security works in Spring Boot 3.x**, covering **auto-configuration, customization, and hands-on authentication setup**. Whether you're new to **Spring Security** or upgrading from an earlier version, this blog will provide **a step-by-step breakdown**. 🚀

---

## **2️⃣ Spring Security Auto-Configuration & Customization**

Spring Boot **automatically configures Spring Security** when you include the `spring-boot-starter-security` dependency. By default, it:

* Enables **basic authentication** with a generated password.
    
* Protects **all endpoints** by default.
    
* Provides a **default user (**`user`) and an auto-generated password.
    

✅ **Default Behavior:** When you run a Spring Boot application with Spring Security, it will prompt you for credentials before accessing any endpoint.

📌 **Spring Security Auto-Configuration:** A feature in Spring Boot that **automatically sets up default security settings**, requiring authentication for all endpoints.

---

## **3️⃣ Understanding SecurityFilterChain**

In **Spring Security 5 and 6**, the old `WebSecurityConfigurerAdapter` class has been **deprecated**, and developers now use **SecurityFilterChain**.

### **🔹 What is SecurityFilterChain?**

SecurityFilterChain is a **bean that defines security rules** for handling authentication and authorization in Spring Security.

✅ **Key Responsibilities:**

* Defines **which endpoints require authentication**.
    
* Configures **how users authenticate** (e.g., in-memory, database, OAuth2).
    
* Specifies **custom security rules**.
    

📌 **SecurityFilterChain:** A **configurable security bean** in Spring Security that **controls authentication, authorization, and security filters**.

---

## **4️⃣ Configuring In-Memory Users & Roles**

If you **don’t have a database yet**, you can use **in-memory authentication** to define users and roles **directly in the security configuration**.

### **🔹 Example: Creating Users with Different Roles**

```java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .requestMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
        )
        .formLogin(withDefaults());
    return http.build();
}

@Bean
public UserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();

    UserDetails admin = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("password")
            .roles("ADMIN")
            .build();

    return new InMemoryUserDetailsManager(user, admin);
}
```

📌 **In-Memory Authentication:** A method where users and roles are **stored in memory instead of a database**.

📌 **UserDetailsService:** An interface in Spring Security that **retrieves user authentication data**.

---

## **5️⃣ Spring Security’s New Lambda-Based Approach (HttpSecurity API)**

Spring Security 6 introduces a **Lambda-based configuration** for `HttpSecurity`, making it **more readable and flexible**.

### **🔹 Old Way (WebSecurityConfigurerAdapter - Deprecated)**

```java
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .antMatchers("/user/**").hasRole("USER")
        .anyRequest().authenticated()
        .and()
        .formLogin();
}
```

### **🔹 New Way (Lambda-Based Approach)**

```java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .requestMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
        )
        .formLogin(Customizer.withDefaults());
    return http.build();
}
```

📌 **HttpSecurity API:** A security configuration class in Spring Security **used to define authentication and authorization rules**.

📌 **Lambda-Based Approach:** A new way of writing Spring Security configurations **in a more readable, functional style**.

---

## **6️⃣ How to Disable Default Security Settings?**

Sometimes, you might need to **disable default security settings** for testing purposes or custom implementations.

### **🔹 Example: Disabling Security Completely**

```java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
    return http.build();
}
```

📌 **Disabling CSRF (Cross-Site Request Forgery):** Useful when working with APIs **without a browser-based client**.

📌 **Permit All Requests:** Allows access to all endpoints **without authentication**.

---

## **7️⃣ ✅ Hands-on: Customizing Authentication with SecurityFilterChain**

### **🔹 Step 1: Add Spring Security Dependency**

Add the following dependency to your `pom.xml`:

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

---

### **🔹 Step 2: Create a Security Configuration Class**

```java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());
        return http.build();
    }
}
```

---

### **🔹 Step 3: Define Users in Memory**

```java
@Bean
public UserDetailsService userDetailsService() {
    UserDetails user = User.withUsername("user")
            .password("password")
            .roles("USER")
            .build();
    return new InMemoryUserDetailsManager(user);
}
```

---

### **🔹 Step 4: Run the Application & Test**

* Start the application.
    
* Open [`http://localhost:8080`](http://localhost:8080).
    
* Log in with **user/password**.
    
* Access different endpoints based on **roles**.
    

---

## **8️⃣ Call to Action**

Want to learn more about **Spring Security?** **Follow me on** [**Bits8Byte**](https://www.bits8byte.com) **for more hands-on tutorials!** 🚀 If you found this helpful, share it with others! 🔥

---
