Authentication

Authentication answers "who are you?": a login request (a name and a password, a token) goes to the AuthenticationManager, which returns the authenticated user or throws an AuthenticationException. For password logins you only write where the users come from, a UserDetailsService; the starter's DaoAuthenticationProvider does the checking, with Spring's guarantees against user enumeration and timing attacks.

Why

A login check looks simple and is easy to get subtly wrong: answering "no such user" faster than "wrong password" tells an attacker which accounts exist; comparing hashes carelessly leaks time; a locked account must stay locked whatever the password. The provider does all of this the way Spring does, and you keep only the part that is yours: loading a user.

Example

// Your user table, as a UserDetailsService.
@Service()
class AccountUsers implements UserDetailsService {
  AccountUsers(this.accounts);

  final AccountRepository accounts;

  @override
  Future<UserDetails> loadUserByUsername(String username) async {
    final row = await accounts.findByEmail(username) ??
        (throw UsernameNotFoundException('No user $username'));
    return User.withUsername(row.email)
        .password(row.passwordHash)          // {argon2}$argon2id$...
        .roles(row.roles)                    // ['ADMIN'] becomes ROLE_ADMIN
        .accountLocked(row.locked)
        .build();
  }
}

With that bean, the auto-configuration builds the AuthenticationManager: a DaoAuthenticationProvider over it, with the PasswordEncoder bean or, without one, the delegating encoder. Inject it to log a user in:

final result = await authenticationManager.authenticate(
  UsernamePasswordAuthenticationToken.unauthenticated('[email protected]', password),
);
SecurityContextHolder.setContext(SecurityContextImpl(result));

On a server, the security starter's form and Basic logins call it for you.

Users

Type What it is
UserDetails A user: username, password (the hash), authorities, and the flags isAccountNonExpired, isAccountNonLocked, isCredentialsNonExpired, isEnabled.
User The standard UserDetails, built with User.withUsername(name) or User.withUserDetails(other).
UserDetailsService loadUserByUsername(name), synchronous or Future; throws UsernameNotFoundException when there is none.
UserDetailsManager Adds createUser, updateUser, deleteUser, userExists.
InMemoryUserDetailsManager A UserDetailsManager over a list, for development and tests.
UserDetailsPasswordService updatePassword(user, newHash): where upgraded hashes are stored.

User.withUsername builder steps: password, passwordEncoder (a function applied to the password at build), roles (adds ROLE_), authorities, authorityNames (written in full), accountExpired, accountLocked, credentialsExpired, disabled, then build().

The AuthenticationManager

Type What it does
AuthenticationManager authenticate(request) returns the authenticated Authentication or throws.
ProviderManager Asks its AuthenticationProviders in order, then an optional parent.
AuthenticationProvider supports(request) and authenticate(request); returns null to let the next provider decide.
DaoAuthenticationProvider The password login over a UserDetailsService and a PasswordEncoder.

What the auto-configuration builds:

A provider of your own, for API keys for example:

@Component()
class ApiKeyProvider implements AuthenticationProvider {
  @override
  bool supports(Authentication authentication) => authentication is ApiKeyToken;

  @override
  Future<Authentication?> authenticate(Authentication authentication) async {
    final key = authentication as ApiKeyToken;
    final client = await clients.findByKey(key.value) ??
        (throw BadCredentialsException('Unknown key'));
    return ApiKeyToken.authenticated(client.name, [SimpleGrantedAuthority('ROLE_CLIENT')]);
  }
}

What DaoAuthenticationProvider guarantees

As Spring's does:

Password checks are bounded

Hashing a password takes hundreds of milliseconds of CPU and, with Argon2, megabytes of memory. On the Dart VM the login's check runs on another isolate, so a login does not stop the server's other requests; on the web it runs in place. The re-hash of an upgraded password runs on the main isolate.

At most spring.security.password-checks.max-concurrent checks run at once (half the processors by default, at least one), and at most max-queued wait (eight times that). Another one fails at once with PasswordChecksBusyException, without spending CPU: the security starter answers it with 503 and Retry-After, never as a failed login. So a flood of wrong passwords takes half the CPU at most. See All properties.

Exceptions

Exception When
BadCredentialsException Wrong name or password.
UsernameNotFoundException Thrown by a UserDetailsService; turned into BadCredentialsException by the provider.
DisabledException, LockedException, AccountExpiredException, CredentialsExpiredException Account status (AccountStatusException).
ProviderNotFoundException No provider supports the request.
AuthenticationServiceException, InternalAuthenticationServiceException The user store failed.
InsufficientAuthenticationException A stronger login is needed.
AuthenticationCredentialsNotFoundException A secured method called with no authentication at all.
AccessDeniedException Logged in, but not allowed.
PasswordChecksBusyException Too many password checks at once; nothing was checked.

Events

Every login publishes an application event: AuthenticationSuccessEvent (and InteractiveAuthenticationSuccessEvent for a web login), or a failure event: AuthenticationFailureBadCredentialsEvent, AuthenticationFailureDisabledEvent, AuthenticationFailureLockedEvent, AuthenticationFailureExpiredEvent, AuthenticationFailureCredentialsExpiredEvent, AuthenticationFailureProviderNotFoundEvent, AuthenticationFailureServiceExceptionEvent. A logout publishes LogoutSuccessEvent.

Listen to them to lock accounts or slow clients down: the packages do not count attempts themselves.

@Component()
class FailedLogins {
  @EventListener()
  void onFailure(AuthenticationFailureBadCredentialsEvent event) =>
      print('failed login for ${event.authentication.name}');
}

In Spring (Java)

@Bean
UserDetailsService users(AccountRepository accounts) {
  return username -> accounts.findByEmail(username)
      .map(row -> User.withUsername(row.email()).password(row.hash()).roles(row.roles()).build())
      .orElseThrow(() -> new UsernameNotFoundException(username));
}

The types and guarantees are Spring Security's. loadUserByUsername may return a Future; authenticate returns a Future. Not here yet: JdbcUserDetailsManager, LDAP, compromised password checking, multi-factor authorities.

See also