spring_boot_starter_security

spring_boot_starter_security secures web applications built with spring_boot_starter_web. A filter chain in front of the controllers decides who may call which endpoint, logs users in (form login, HTTP Basic, bearer tokens, single sign-on), protects browser sessions against CSRF, and sends the headers that keep browsers safe. It is the Dart port of Spring Boot's spring-boot-starter-security.

Why

A server with any endpoint that is not public must know who is calling, refuse what that user may not do, keep a page on another site from using the user's session, and send safe headers. Writing those checks in every controller is easy to get wrong. With this starter they live in one place, run before any controller, and are on as soon as the dependency is listed.

Setup

# pubspec.yaml
dependencies:
  spring_boot_starter_security: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0
  spring_boot_starter_test: ^0.9.0     # MockMvc, springBootTest
  test: ^1.33.0

It brings the web starter, spring_security_core (users, password hashes, @PreAuthorize on bean methods) and spring_boot_starter_oauth2_client (the registrations of single sign-on), so this one dependency is enough. One import: package:spring_boot_starter_security/spring_boot_starter_security.dart, which re-exports all three.

Example

import 'package:spring_boot_starter_security/spring_boot_starter_security.dart';

import 'spring_gen/main.spring.dart';

@Configuration()
class SecurityConfig {
  @Bean()
  SecurityFilterChain filterChain(HttpSecurity http) => http
      .authorizeHttpRequests((auth) => auth
          .requestMatchers('/public/**').permitAll()
          .requestMatchers('/api/admin/**').hasRole('ADMIN')
          // Anyone may read the catalogue; changing it needs a login.
          .requestMatchersFor(HttpMethod.get, ['/api/books/**']).permitAll()
          .anyRequest().authenticated())
      .formLogin()
      .httpBasic()
      .build();

  // The users and their hashed passwords.
  @Bean()
  UserDetailsService users() => InMemoryUserDetailsManager([
        User.withUsername('ada').password('{argon2}\$argon2id\$v=19\$...').roles(['ADMIN']).build(),
      ]);
}

@RestController()
class MeController {
  @GetMapping('/me')
  String me(Authentication authentication) => authentication.name;
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
curl -i localhost:8080/me
# HTTP/1.1 401 Unauthorized
# www-authenticate: Basic realm="Realm"

curl -u ada:secret localhost:8080/me
# ada

Secure by default

With the starter listed and nothing configured, as in Spring Boot:

# A development user instead of the generated password.
spring.security.user.name=admin
spring.security.user.password=change-me
spring.security.user.roles=ADMIN

The default user disappears as soon as the application has its own users: a UserDetailsService, an AuthenticationProvider, an AuthenticationManager or a JwtDecoder bean, the JWT properties, or an OAuth2 client registration (unless spring.security.user.name or .password is set).

What is inside

Configuring:

Tokens and single sign-on:

Using it:

Reference:

In Spring (Java)

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  return http
      .authorizeHttpRequests(auth -> auth
          .requestMatchers("/public/**").permitAll()
          .requestMatchers("/api/admin/**").hasRole("ADMIN")
          .requestMatchers(HttpMethod.GET, "/api/books/**").permitAll()
          .anyRequest().authenticated())
      .formLogin(Customizer.withDefaults())
      .httpBasic(Customizer.withDefaults())
      .build();
}

Differences that matter:

See also