
# The security context

Every security check reads the current user from the security context, which `SecurityContextHolder` keeps. Code never passes the user around: a service deep in the call stack asks the holder, and gets the user of the request (on a server) or of the app (in Flutter).

## Why

Passing the user as a parameter through every layer is tedious and easy to forget. Keeping it in a global variable is wrong on a server, where many requests run at once. Spring keeps it per thread. Dart has one thread and switches between requests at each `await`, so the context is kept per `Zone`: each request sees only its user, also after an `await`.

## Example

```dart
// Read who is calling, anywhere.
final authentication = SecurityContextHolder.getContext().authentication;
print(authentication?.name);

// A Flutter app logs the user in and keeps the result.
final result = await authenticationManager.authenticate(
  UsernamePasswordAuthenticationToken.unauthenticated(name, password),
);
SecurityContextHolder.setContext(SecurityContextImpl(result));

// ...and logs out.
SecurityContextHolder.clearContext();

// A nightly job calls secured services as a system user.
await SecurityContextHolder.runWithContext(
  () => reports.rebuildAll(),
  SecurityContextImpl(
    UsernamePasswordAuthenticationToken.authenticated(
      'system',
      null,
      [SimpleGrantedAuthority('ROLE_ADMIN')],
    ),
  ),
);
```

## The holder

| Call | What it does |
|---|---|
| `SecurityContextHolder.getContext()` | The current context; an empty one is created when there is none, so the result is never `null`. |
| `SecurityContextHolder.setContext(context)` | Makes `context` the current one, in the current scope only. |
| `SecurityContextHolder.clearContext()` | Removes the current context: a logout. |
| `SecurityContextHolder.runWithContext(body, [context])` | Runs `body` with its own context (empty when omitted) and returns what it returns. |
| `SecurityContextHolder.setContextHolderStrategy(strategy)` | Replaces the strategy; rarely needed. |

A `SecurityContext` holds one `authentication`, or `null` when nobody is logged in. At a login, prefer storing a new `SecurityContextImpl` over changing the current one: a context object may be shared with other code.

## Scopes

The default strategy, `ZoneSecurityContextHolderStrategy`, suits servers and Flutter apps alike:

- **Each `runWithContext` scope has its own context.** It is current in `body` and in everything `body` starts (`await`, timers, streams), and gone afterwards. Changes made inside (a login, `clearContext`) stay inside. Scopes running at the same time, such as two requests, never mix.
- **On a server**, the security starter runs each request in a scope of its own.
- **Outside every scope** there is one context for the whole program: in a Flutter app, that is the logged-in user.
- **On a server, an authentication set outside every scope stays**: all the code that runs outside a request (scheduled work, timers, listeners) then acts as that user. `onProgramWideAuthentication` of the strategy is told each time one is set there, with the place, and `programWideAuthentication` is who is there now. The security starter logs a WARN through it and can show it in the health (see [spring_boot_starter_security](../spring-boot-starter-security/index.md)). Nothing is refused. Spring has no such report.

`GlobalSecurityContextHolderStrategy` keeps one context for everything. With it, `runWithContext` puts the previous context back as soon as `body` returns, so for an `async` body at its first `await`: use it only for synchronous programs.

## The Authentication

| Member | Meaning |
|---|---|
| `name` | The user's name. |
| `principal` | The user: a `UserDetails` after a password login, a `Jwt` for a bearer token, an `OAuth2User` after single sign-on. |
| `credentials` | The password or token; erased after a login, and never readable in expressions. |
| `authorities` | The `GrantedAuthority` list: `ROLE_ADMIN`, `SCOPE_orders.read`. |
| `isAuthenticated` | Whether it was checked. |

`UsernamePasswordAuthenticationToken.unauthenticated(name, password)` is a login request; `UsernamePasswordAuthenticationToken.authenticated(principal, credentials, authorities)` is a logged-in user. `AnonymousAuthenticationToken` is the anonymous user of a web request without a login.

## Listening to logins and logouts

Wrap the strategy in a `ListeningSecurityContextHolderStrategy` with `SecurityContextChangedListener`s: each `setContext` and `clearContext` hands them a `SecurityContextChangedEvent` with the contexts before and after.

```dart
class LoginAudit implements SecurityContextChangedListener {
  @override
  void securityContextChanged(SecurityContextChangedEvent event) =>
      print('now: ${event.newContext?.authentication?.name}');
}

// Once at startup.
SecurityContextHolder.setContextHolderStrategy(
  ListeningSecurityContextHolderStrategy(
    SecurityContextHolder.getContextHolderStrategy(),
    [LoginAudit()],
  ),
);
```

Only changes made through the holder are seen: code that changes the `authentication` of a context object in place does not notify. Changes inside a `runWithContext` scope are reported too.

`spring_boot_starter_flutter_security` does this so that widgets follow the logged-in user.

## In Spring (Java)

```java
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
```

The names are Spring Security's. The context is kept per `Zone` instead of per thread, and `runWithContext` replaces the `DelegatingSecurityContextRunnable` family for running work as a user.

## See also

- [Authentication](authentication.md)
- [Method security](method-security.md)
- [Testing](testing.md)
