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

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

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