🔐 What is Spring Security? How to Implement Spring Security in Spring Boot?

Spring Security is a powerful framework used to protect Java applications.
It provides features like:

  • User authentication (e.g., login)
  • User authorization (e.g., roles like ADMIN, USER)
  • Protection against common attacks (like CSRF, XSS)
  • Password encryption

In short, It helps you control who can access what in your app.

⚙️ How to Implement Spring Security in Spring Boot?

✅ Step 1: Add Dependency

In pom.xml (for Maven):

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

✅ Step 2: Default Security

When you add the dependency, Spring Boot automatically secures all URLs and sets up a default login page with a generated password (check logs on startup).

✅ Step 3: Create Your Own User (In-Memory)

@Configuration
public class SecurityConfig {
    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("1234")
            .roles("ADMIN")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

✅ Step 4: Secure Endpoints

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

👨💻 Example Flow:

  • Visit /admin/home → You’ll see a login page.
  • Enter admin / 1234 → Access granted if credentials are valid.

✅ Bonus Features

  • Use JWT for stateless APIs
  • Connect to database-based users
  • Customize login/logout pages
  • Add role-based access
Back to blog

Leave a comment