Testing
package:spring_security_core/testing.dart runs code as a given user, in a scope of its own, so tests running at the same time do not see each other's user. Use it to test @PreAuthorize rules and any code that reads the current user.
Why
A secured method needs a user in the security context. Setting the global context in a test leaks into the next test, and into tests running at the same time. These helpers set the user only for the code they run, through SecurityContextHolder.runWithContext, and nothing remains afterwards.
Example
import 'package:spring_security_core/testing.dart';
import 'package:test/test.dart';
void main() {
test('admins cancel any order', () async {
await withMockUser(() => orders.cancel(order), roles: ['ADMIN']);
});
test('users cannot cancel orders of others', () async {
await expectLater(
withMockUser(() => orders.cancel(othersOrder)), // user, ROLE_USER
throwsA(isA<AccessDeniedException>()),
);
});
test('nobody logged in', () async {
await expectLater(
orders.cancel(order),
throwsA(isA<AuthenticationCredentialsNotFoundException>()),
);
});
}
The helpers
| Helper | Runs the body as |
|---|---|
withMockUser(body, {username, roles, authorities}) |
A User named username (default user) with roles (default ['USER'], so ROLE_USER), or with authorities written in full. |
withAuthentication(body, authentication) |
Any Authentication: your own UserDetails, a JWT, an OAuth2 user. |
withAnonymousUser(body) |
The anonymous user a web request without a login has. |
Each returns a Future of what body returns, and accepts a synchronous or async body.
final me = User.withUsername('ada').password('x').authorityNames(['SCOPE_orders.read']).build();
await withAuthentication(
() => orders.mine(),
UsernamePasswordAuthenticationToken.authenticated(me, null, me.authorities),
);
One user never sees another's
A server runs every request on one event loop: at each await another request goes on. A bean that remembers the user in a field, a cache whose key has no user in it, a result shared between callers: each hands one user what belongs to another, and only when two requests overlap. withMockUsersAtOnce makes them overlap.
test('everybody gets their own orders', () async {
final found = await withMockUsersAtOnce(
['ada', 'bob', 'eve'],
(username) => orders.mine(),
);
for (final MapEntry(key: username, value: results) in found.entries) {
for (final orders in results) {
expect(orders.map((o) => o.owner).toSet(), {username});
}
}
expect(programWideAuthentication(), isNull);
});
| Helper | What it does |
|---|---|
withMockUsersAtOnce(usernames, body, {rounds, roles}) |
Runs body as each user rounds times (default 10), all at the same time, the calls starting a few turns of the event loop apart in a changing pattern. Returns what every call gave, by user. A call that fails fails the whole, once all have ended. |
programWideAuthentication() |
The authentication left outside every scope: null on a server unless the application means otherwise. |
With MockMvc, make the request in the body: mvc.perform(... ..with_(user(username))). Spring's test support has no counterpart: a thread per request hides what a single event loop shows.
In a Spring test
In a @SpringBootTest class, call the helpers inside the test methods; they work with beans from the context. For web requests through MockMvc, the security starter's testing.dart has request post-processors (user('ada'), jwt(), csrf()) and re-exports these helpers (see spring_boot_starter_security).
In Spring (Java)
@Test
@WithMockUser(roles = "ADMIN")
void adminsCancelAnyOrder() { orders.cancel(order); }
The helpers are functions instead of the annotations @WithMockUser, @WithSecurityContext and @WithAnonymousUser.