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:
- every request needs a login;
- a browser asking for a page is redirected to a generated login page,
/login; programs andcurlget a401withWWW-Authenticate: Basic; scripts (X-Requested-With: XMLHttpRequest) get a plain401, so no browser password dialog appears; - there is one user,
user, whose password isspring.security.user.passwordor, when that is not set, a random one logged at startup (for development only); - CSRF protection, security headers, CORS with the router's rules, and logout at
POST /logoutare on; - a firewall refuses ambiguous paths before any rule is looked at.
# 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:
- The filter chain:
SecurityFilterChain,HttpSecurity, several chains, your own filters. - Request rules:
authorizeHttpRequests, matchers,access(...). - Form login and HTTP Basic: the generated pages, your own login page, logout.
- Sessions: session fixation,
stateless, the limit per user. - CSRF: tokens for forms, single-page apps and Flutter web.
- Headers and CORS: HSTS, CSP, frame options, the router's CORS rules.
Tokens and single sign-on:
- JWT resource servers: bearer tokens from an identity provider.
- DPoP-bound tokens: tokens bound to the client's key.
- Single sign-on:
oauth2Login(), Google, Apple, OpenID Connect logout.
Using it:
- In controllers:
Authentication,@AuthenticationPrincipal, method security. - Testing:
MockMvcas a user,csrf(),jwt(). - Firewall and limits: refused paths and the bounds on work per request.
Reference:
- All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring Security.
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:
requestMatchers(HttpMethod, ...)isrequestMatchersFor: Dart has no overloading.- A request that no rule matches is denied.
- CORS is on by default, with the router's rules.
- Only a login makes a session; the CSRF token and the saved request are signed cookies.
- The full list is on Differences from Spring.