
# Widgets that follow the user

A few widgets and a bean follow who is logged in: `context.principal` and `PrincipalBuilder` rebuild on every login and logout, and `PrincipalView` shows a child only for a user that matches a role, an authority or a SpEL expression. They are for display only: the server checks access.

## Why

The app is in the user's hands (it can be patched, the API called directly), so hiding a button protects nothing; the server's checks (a 403) do. These widgets only spare the user buttons that would fail, like Thymeleaf's `sec:authorize`, which only decides what a page renders. They are named after the principal (Spring's word for who is logged in), not after security, so they promise no protection.

## Example

```dart
// A header that greets the user, or offers a login.
PrincipalBuilder(
  builder: (context, authentication) => authentication == null
      ? const LoginButton()
      : Text('Hello, ${authentication.name}'),
)

// An admin menu, for admins only.
PrincipalView(
  hasRole: 'ADMIN',
  child: const AdminMenu(),
  otherwise: const SizedBox.shrink(),
)

// Any widget: rebuilt when the user changes.
Text('Hello, ${context.principal?.name ?? 'guest'}');
```

## The parts

- **`PrincipalNotifier`**, a bean: the current `Authentication` as a `Listenable`, changed on every login and logout. It listens to the `SecurityContextHolder` (through Spring Security's `ListeningSecurityContextHolderStrategy`) and to the authentication events of `OAuth2LoginService` and the `AuthenticationManager`. Work run as another user (`runWithContext`) does not count, and an anonymous user counts as nobody.
- **`context.principal`** reads it in `build` and builds the widget again when it changes, in any widget.
- **`PrincipalBuilder(builder:)`** builds with the current authentication, `null` when nobody is logged in.
- **`PrincipalView`** shows `child` for a principal that matches and `otherwise` (nothing by default) else.

| `PrincipalView` parameter | Meaning |
|---|---|
| `hasRole` | The user has this role (`ADMIN` is the authority `ROLE_ADMIN`) |
| `hasAuthority` | The user has this authority (`SCOPE_admin`) |
| `authenticated` | `true`: someone is logged in; `false`: only for nobody |
| `expression` | A SpEL expression as in `@PreAuthorize`: `"hasRole('ADMIN') or hasAuthority('SCOPE_admin')"` |
| `child` | Shown when every given condition holds |
| `otherwise` | Shown else; nothing by default |

The conditions are evaluated by the application's `MethodSecurityExpressionHandler`, so the role hierarchy applies.

## In Spring (Java)

Spring has no widgets; the nearest are Thymeleaf's `sec:authorize` and `sec:authentication`, which decide what a server page renders.

## See also

- [Guarded screens](guarded-screens.md)
- [Login screens](login-screens.md)
- [spring_security_core](../spring-security-core/index.md)
