Spring Security in Spring Boot 2.x Using WebSecurityConfigurerAdapter

Amandeep Singh
3 min read5 days ago

--

Spring Security is a powerful authentication and access-control framework for Java applications. With Spring Boot 2.x, the most common way to customize security was by extending WebSecurityConfigurerAdapter. This allowed developers to define security configurations tailored to their application's needs.

⚠️ Note: WebSecurityConfigurerAdapter was deprecated in Spring Boot 2.7 and removed in Spring Boot 3. However, this guide focuses on Spring Boot 2.x, where it was widely used.

https://www.interviewbit.com/spring-security-interview-questions/

How Spring Security Works in Spring Boot

Spring Security operates by integrating with Spring Boot’s auto-configuration and setting up a security filter chain that intercepts every HTTP request. It provides:

Authentication: Verifies user identity using credentials (e.g., username/password, JWT, OAuth, etc.).
Authorization: Controls access to resources based on roles and permissions.
CSRF Protection: Prevents cross-site request forgery attacks.
Session Management: Handles user sessions securely.

By default, Spring Security secures all endpoints, requiring authentication for access.

Implementing Security Using WebSecurityConfigurerAdapter

To customize security, we extend WebSecurityConfigurerAdapter and override its methods to define our security rules.

1️⃣ Add Spring Security Dependency

If you’re using Maven, include:

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

For Gradle:

implementation 'org.springframework.boot:spring-boot-starter-security'

Create a Custom Security Configuration

Create a class that extends WebSecurityConfigurerAdapter:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 1️⃣ Define User Authentication
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN")
.and()
.withUser("user").password(passwordEncoder().encode("user123")).roles("USER");
}

// 2️⃣ Define Authorization Rules
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // Disable CSRF for simplicity (Not recommended for production)
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // Only ADMIN can access /admin/**
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN") // USER or ADMIN can access /user/**
.antMatchers("/").permitAll() // Public access
.anyRequest().authenticated() // All other requests require authentication
.and()
.formLogin() // Enable default login form
.and()
.logout(); // Enable logout
}

// 3️⃣ Define Password Encoder
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

🔑 1. Authentication Configuration (configure(AuthenticationManagerBuilder auth))

This method sets up in-memory authentication, where we define users and roles.

  • withUser("admin"): Defines a user named admin with password admin123 and role ADMIN.
  • passwordEncoder().encode("password"): Ensures passwords are encoded securely using BCrypt.
  • We also define a user role with different credentials.

💡 In real-world applications, you would configure authentication using a database or external provider.

🔐 2. Authorization Rules (configure(HttpSecurity http))

Here, we define who can access what:

/admin/** → Accessible only by users with ADMIN role.
/user/** → Accessible by both USER and ADMIN roles.
/ → Open to everyone (public access).
anyRequest().authenticated() → All other endpoints require authentication.

We also enable:

  • Form-based login (formLogin()) → Users get a default login page.
  • Logout support (logout()) → Allows users to log out.
  • Disabling CSRF (csrf().disable()) → Not recommended for production but simplifies API testing.

🛠️ Testing the Security Setup

Once you run the application, Spring Security:

1️⃣ Auto-generates a login page at http://localhost:8080/login.
2️⃣ Enter the credentials:

  • admin/admin123 → Access /admin/** and /user/**
  • user/user123 → Access only /user/**
  • Public pages (e.g., /) remain accessible without authentication.

WebSecurityConfigurerAdapter is Deprecated! What Now?

Since Spring Boot 2.7+, WebSecurityConfigurerAdapter is deprecated, and security configurations are done using Lambda-based DSL:

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

return http.build();
}

You can check-out detailed video for Springboot 3.xx Security Implementation:

Follow for more such content and Subscribe to my Youtube Channel for Weekly Tech Dose:

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Amandeep Singh
Amandeep Singh

Written by Amandeep Singh

Love Programming & Love to Share the Knowledge with Others

No responses yet

Write a response