
# 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

```dart
// 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:

```dart
final result = await authenticationManager.authenticate(
  UsernamePasswordAuthenticationToken.unauthenticated('ada@example.com', 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 `AuthenticationProvider`s 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:

- with a `UserDetailsService` bean: a `DaoAuthenticationProvider` over it;
- with `AuthenticationProvider` beans: a `ProviderManager` over all of them;
- with an `AuthenticationManager` bean of your own: yours, untouched.

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

```dart
@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:

- an unknown user and a wrong password fail the same way (`BadCredentialsException`), and an unknown user still checks the password against a dummy hash, so neither the answer nor its time tells whether the user exists;
- locked, disabled and expired accounts fail before the password check, an expired password after it;
- a stored hash that no encoder understands (such as `{bcrypt}`) fails as a wrong password, with a warning in the log; it never logs in;
- a hash made with older settings (another `{id}`, weaker parameters) is re-hashed after a successful login and stored through the `UserDetailsPasswordService` bean, or the user service itself when it is one;
- the result's principal is the loaded `UserDetails`, with its authorities, and its credentials are erased.

## 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](properties.md).

## 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.

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

## In Spring (Java)

```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

- [Password encoders](password-encoders.md)
- [The security context](security-context.md)
- [Events](../spring-core-dart/events/index.md)
