0
0
SpringbootHow-ToBeginner · 4 min read

How to Add Spring Security to Your Project Quickly

To add Spring Security to your project, include the spring-boot-starter-security dependency in your build file and create a security configuration class that extends WebSecurityConfigurerAdapter or uses the new SecurityFilterChain bean. This setup enables basic authentication and protects your application endpoints.
📐

Syntax

Adding Spring Security involves two main steps: adding the dependency and configuring security rules.

  • Dependency: Add spring-boot-starter-security to your pom.xml (Maven) or build.gradle (Gradle).
  • Configuration: Create a Java class to define security rules, either by extending WebSecurityConfigurerAdapter (legacy) or defining a SecurityFilterChain bean (modern).
java
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

// Modern configuration example
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .anyRequest().authenticated()
        )
        .httpBasic();
    return http.build();
}
💻

Example

This example shows a minimal Spring Boot application with Spring Security that requires basic authentication for all endpoints.

java
package com.example.securitydemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class SecurityDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityDemoApplication.class, args);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @RestController
    class HelloController {
        @GetMapping("/")
        public String hello() {
            return "Hello, secured world!";
        }
    }
}
Output
When you run this app and visit http://localhost:8080/, the browser prompts for username and password. Use the default Spring Boot user and password printed in the console to see the message: "Hello, secured world!"
⚠️

Common Pitfalls

  • Forgetting to add the spring-boot-starter-security dependency means no security features are enabled.
  • Using the legacy WebSecurityConfigurerAdapter class is deprecated since Spring Security 5.7; prefer SecurityFilterChain bean configuration.
  • Not configuring any authorization rules defaults to securing all endpoints, which can confuse beginners expecting open access.
  • Ignoring the default generated password printed in the console causes login failures.
java
/* Legacy (deprecated) approach - avoid this in new projects */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

/* Modern recommended approach */
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .httpBasic();
    return http.build();
}
📊

Quick Reference

Summary tips for adding Spring Security:

  • Add spring-boot-starter-security dependency.
  • Use SecurityFilterChain bean for configuration.
  • Secure endpoints with authorizeHttpRequests and httpBasic for basic auth.
  • Check console for default user credentials or configure your own users.

Key Takeaways

Add the spring-boot-starter-security dependency to enable Spring Security features.
Configure security using a SecurityFilterChain bean instead of the deprecated WebSecurityConfigurerAdapter.
By default, all endpoints require authentication with a generated user and password.
Use httpBasic() for simple username/password authentication in development.
Check the application startup logs for the default user credentials or configure custom users.