Testing

package:spring_boot_starter_security/testing.dart makes MockMvc requests as a given user, without a real login, and passes the CSRF check on demand. The security chain still runs: rules, headers and CSRF are checked as in production.

Why

A test of a secured endpoint must say who calls it. Logging in for real in every test is slow and couples each test to the login. Request post-processors put the user in the request directly, so a test reads "an admin may open the admin API" in one line.

Example

import 'package:spring_boot_starter_security/testing.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/main.test.spring.dart';

void main() {
  final app = springBootTest(springApplication);

  test('an admin may open the admin API', () async {
    await app.mockMvc
        .perform(MockRequestBuilder(HttpMethod.get, '/api/admin')
          ..with_(user('ada').roles(['ADMIN'])))
        .andExpect(status: 200);
  });

  test('a user may not', () async {
    await app.mockMvc
        .perform(MockRequestBuilder(HttpMethod.get, '/api/admin')..with_(user('bob')))
        .andExpect(status: 403);
  });

  test('a POST needs a CSRF token as well as a user', () async {
    await app.mockMvc
        .perform(MockRequestBuilder(HttpMethod.post, '/api/books')
          ..with_(user('ada'))
          ..with_(csrf()))
        .andExpect(status: 201);
  });

  test('a token with the right scope', () async {
    await app.mockMvc
        .perform(MockRequestBuilder(HttpMethod.get, '/api/orders')
          ..with_(jwt().subject('ada').claim('scope', 'orders.read')))
        .andExpect(status: 200);
  });
}

Request post-processors

Post-processor The request runs as
user('ada') A logged-in user ada with ROLE_USER. .roles(['ADMIN']) replaces the roles (without ROLE_), .authorities(['SCOPE_read']) sets full authorities, .password('x') the password.
userDetails(user) Your own UserDetails as the principal.
authentication(authentication) Any Authentication, such as a custom token.
anonymous() The anonymous user (anonymousUser, ROLE_ANONYMOUS).
jwt() A valid JWT bearer token, not decoded: subject user, scope read (SCOPE_read), issued now, expiring in 5 minutes. .subject(...), .claim(name, value) and .authorities([...]) change it. The authorities come from the default converter, not the application's jwt.* properties.
httpBasic('ada', 'secret') An Authorization: Basic header: the real login runs against the application's users. Use it to test the login itself.
csrf() Passes the CSRF check as if a valid token was sent; .useInvalidToken() makes it fail with 403.

Requests other than GET, HEAD, TRACE and OPTIONS need csrf() while CSRF protection is on. The CSRF post-processor sets a request attribute that lives on the server side only: no client can set it, so it is not a way around the check.

Method security

The library re-exports withMockUser, withAuthentication and withAnonymousUser from spring_security_core, to call secured services directly (see Testing in spring_security_core):

test('admins cancel any order', () async {
  final orders = app.getBean<OrderService>();
  await withMockUser(() => orders.cancel(order), roles: ['ADMIN']);
});

In Spring (Java)

mockMvc.perform(get("/api/admin").with(user("ada").roles("ADMIN"))).andExpect(status().isOk());
mockMvc.perform(post("/api/books").with(user("ada")).with(csrf())).andExpect(status().isCreated());

The post-processors are spring-security-test's. with is with_ (a Dart keyword). Not here yet: the oauth2Login() and oidcLogin() post-processors and the authenticated() result matchers.

See also