withAuthentication<T> function

Future<T> withAuthentication<T>(
  1. FutureOr<T> body(),
  2. Authentication authentication
)

Runs body with authentication as the current user and returns its result.

Use it when the test needs a specific principal, such as your own UserDetails class or a JWT token.

Spring (Java): @WithSecurityContext.

Implementation

Future<T> withAuthentication<T>(
  FutureOr<T> Function() body,
  Authentication authentication,
) => SecurityContextHolder.runWithContext(
  () async => await body(),
  SecurityContextImpl(authentication),
);