spring_security_core

spring_security_core is the part of security that does not depend on HTTP: who is logged in, users and their password hashes, the login check, and access rules on bean methods (@PreAuthorize, @PostAuthorize, @Secured, @PreFilter and @PostFilter). It is the Dart port of Spring Security's core and method security.

Why

An application must know its user and check what that user may do, wherever the call comes from: a web request, a scheduled job, a button in a Flutter app. With this package the rules sit on the methods they protect, one line each, instead of if checks spread over the code. Passwords are stored as slow, salted hashes in Spring Security's formats, so a Dart and a Java service can share a user table.

Setup

# pubspec.yaml
dependencies:
  spring_security_core: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # writes the proxies method security needs

It brings and re-exports spring_boot_dart and the logging starter, so the application lists it (or the security starter) alone. One import is enough: package:spring_security_core/spring_security_core.dart.

Example

import 'package:spring_security_core/spring_security_core.dart';

@Service()
class OrderService {
  OrderService(this.orders);

  final OrderRepository orders;

  // Admins cancel any order, other users only their own.
  @PreAuthorize("hasRole('ADMIN') or #order.owner == principal.username")
  Future<void> cancel(Order order) => orders.delete(order);

  // Each user gets only their own orders out of the list.
  @PostFilter('filterObject.owner == authentication.name')
  Future<List<Order>> all() => orders.findAll();
}

@Configuration()
class Users {
  // The users and their hashed passwords.
  @Bean()
  UserDetailsService users() => InMemoryUserDetailsManager([
        User.withUsername('ada').password('{argon2}\$argon2id\$v=19\$...').roles(['ADMIN']).build(),
        User.withUsername('bob').password('{argon2}\$argon2id\$v=19\$...').roles(['USER']).build(),
      ]);
}
// A Flutter app logs the user in and keeps the result.
final result = await authenticationManager.authenticate(
  UsernamePasswordAuthenticationToken.unauthenticated(name, password),
);
SecurityContextHolder.setContext(SecurityContextImpl(result));

await orderService.cancel(order); // checked against the logged-in user

What starts

What is inside

In Spring (Java)

@EnableMethodSecurity
@Configuration
class SecurityConfig {}

@Service
class OrderService {
  @PreAuthorize("hasRole('ADMIN') or #order.owner == principal.username")
  public void cancel(Order order) { ... }
}

Differences that matter:

See also