Securing a Spring Boot App: form login

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Add the dependency

Adding one starter secures the whole application immediately:

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

Restart the app and every endpoint now requires login. Spring Boot generates a default user user and prints a random password in the console – proof the filter chain is active.

Configure your own rules

Replace the defaults by defining a SecurityFilterChain bean:

@Configuration
public class SecurityConfig {

  @Bean
  SecurityFilterChain chain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/", "/public/**").permitAll()
        .anyRequest().authenticated())
      .formLogin(form -> form
        .loginPage("/login").permitAll())
      .logout(logout -> logout.permitAll());
    return http.build();
  }
}

Reading the rules: the home page and anything under /public are open, every other request needs an authenticated user, and unauthenticated users are sent to /login.

How the bean is read

The HttpSecurity builder is a fluent DSL. Order matters for the request matchers – the first rule that matches a URL wins – so put specific permitAll() paths before the catch-all anyRequest().authenticated().

Key points

  • The security starter secures every endpoint out of the box.
  • Define a SecurityFilterChain bean to declare your own access rules.
  • authorizeHttpRequests maps URL patterns to access rules; first match wins.
  • formLogin enables a login page; permitAll() opens public paths.
Share this post:

Comments (0)

Please login or register to comment.