Security Configuration (Spring Security DSL)

About

Spring Security DSL (Domain-Specific Language) is the modern way to configure security in Spring Boot without extending WebSecurityConfigurerAdapter. It was introduced in Spring Security 5 and became the default approach in Spring Boot 3.

This approach uses lambda-based security configuration to define authentication, authorization, and other security settings more concisely.

Spring Security DSL -

  • Eliminates WebSecurityConfigurerAdapter – No need to override configure().

  • More readable and flexible – Uses fluent, declarative API.

  • Better compatibility with functional and reactive programming.

  • Aligns with Spring Boot's convention-over-configuration philosophy.

Components of Spring Security Configuration

Spring Security DSL is built on several core components:

Component

Description

SecurityFilterChain

Defines HTTP security rules.

HttpSecurity

Configures security settings.

AuthenticationManager

Handles authentication logic.

UserDetailsService

Loads user details from DB.

PasswordEncoder

Encrypts and verifies passwords.

AuthenticationProvider

Custom authentication logic.

SecurityContext

Holds authenticated user details.

Security Configuration

Before (Spring Boot 2 - Extending WebSecurityConfigurerAdapter)

  • Uses the old WebSecurityConfigurerAdapter class (deprecated in Spring Boot 3).

After (Spring Boot 3 - Using Security DSL)

  • Uses SecurityFilterChain with HttpSecurity DSL instead of extending WebSecurityConfigurerAdapter.

  • requestMatchers() replaces antMatchers().

Examples

1. Configuring Authentication (In-Memory Users)

  • Defines users in-memory (for testing).

  • Uses BCryptPasswordEncoder for secure password hashing.

2. Configuring Authentication (Database UserDetailsService)

  • Retrieves users and roles from database dynamically.

3. Defining Custom AuthenticationManager

  • Custom AuthenticationManager with UserDetailsService and PasswordEncoder.

4. Role-Based Authorization

  • Restricts /admin to ROLE_ADMIN and /user to ROLE_USER.

5. Permission-Based Authorization

  • Uses fine-grained permission-based access control.

6. Enabling JWT-Based Authentication

  • Integrates JWT authentication into Spring Security filter chain.

Last updated