Spring Security for WebFlux: the same rules on a non-blocking stack

A WebFlux application handles many requests on a few threads, so the security tools that rely on a ThreadLocal do not work there. Spring Security has a reactive version of each piece: a WebFilter chain, a security context carried in the Reactor context, and method security that returns Mono and Flux. This page runs each one in a Spring Boot 4.1 application and shows where code written for Spring MVC stops working.

Contents

What changes when the stack is reactive

In Spring MVC, each request runs on one thread from start to finish, and Spring Security keeps the logged-in user in a ThreadLocal. WebFlux breaks that assumption: a request starts on one event-loop thread, waits for I/O without holding a thread, and continues on whichever thread is free. A value stored in a ThreadLocal would be lost, or worse, seen by another request that later runs on the same thread.

Spring Security therefore has a reactive counterpart for every servlet piece:

Servlet and reactive Spring Security
PurposeSpring MVC (servlet)WebFlux (reactive)
Filter chain beanSecurityFilterChainSecurityWebFilterChain
Configuration DSLHttpSecurity, authorizeHttpRequests, requestMatchers, anyRequestServerHttpSecurity, authorizeExchange, pathMatchers, anyExchange
Enabling annotation@EnableWebSecurity@EnableWebFluxSecurity
Loading usersUserDetailsServiceReactiveUserDetailsService, returning Mono<UserDetails>
Checking credentialsAuthenticationManagerReactiveAuthenticationManager
Current userSecurityContextHolder, a ThreadLocalReactiveSecurityContextHolder, stored in the Reactor Context
Method security@EnableMethodSecurity@EnableReactiveMethodSecurity; methods return Mono or Flux
JWT decoderJwtDecoderReactiveJwtDecoder
Test clientMockMvc with SecurityMockMvcRequestPostProcessorsWebTestClient with SecurityMockServerConfigurers

Spring Boot chooses between the two from the classpath: with spring-boot-starter-webflux and no servlet stack, it applies the reactive security auto-configuration, which locks every endpoint with HTTP Basic and a form login, just as on the servlet side. The examples run Spring Boot 4.1 with Reactor Netty and Spring Security 7.1. Each application starts on a random port, calls itself with java.net.http.HttpClient or WebTestClient, and stops.

URL rules with SecurityWebFilterChain

The reactive DSL reads almost exactly like the servlet one, with different method names. This program sets up the same three-tier rules as the Spring Security page and calls each endpoint as an anonymous client, a user and an admin:

Java
package demo.reactive.rules;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

public class ReactiveRules {

    @RestController
    static class Endpoints {
        @GetMapping("/public/info")
        Mono<String> info() {
            return Mono.just("open to everyone");
        }

        @GetMapping("/api/orders")
        Mono<String> orders() {
            return Mono.just("orders");
        }

        @GetMapping("/admin/stats")
        Mono<String> stats() {
            return Mono.just("stats");
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @EnableWebFluxSecurity
    @Import(Endpoints.class)
    static class App {
        @Bean
        SecurityWebFilterChain security(ServerHttpSecurity http) {
            return http
                    .authorizeExchange(ex -> ex
                            .pathMatchers("/public/**").permitAll()
                            .pathMatchers("/admin/**").hasRole("ADMIN")
                            .anyExchange().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .build();
        }

        @Bean
        MapReactiveUserDetailsService users() {
            return new MapReactiveUserDetailsService(
                    User.withUsername("ann").password("{noop}ann-pw").roles("USER").build(),
                    User.withUsername("root").password("{noop}root-pw").roles("ADMIN").build());
        }
    }

    static String call(String base, String path, String user) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (user != null) {
            request.header("Authorization", "Basic "
                    + Base64.getEncoder().encodeToString(user.getBytes()));
        }
        HttpResponse<String> r = HttpClient.newHttpClient()
                .send(request.build(), HttpResponse.BodyHandlers.ofString());
        return r.statusCode() + (r.statusCode() == 200 ? " " + r.body() : "");
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            System.out.println("Server: " + context.getClass().getSimpleName());
            for (String path : new String[] {"/public/info", "/api/orders", "/admin/stats"}) {
                System.out.println(path);
                for (String user : new String[] {null, "ann:ann-pw", "root:root-pw"}) {
                    String who = user == null ? "anonymous" : user.substring(0, user.indexOf(':'));
                    System.out.printf("  %-9s -> %s%n", who, call(base, path, user));
                }
            }
        }
    }
}
Output
Server: AnnotationConfigReactiveWebServerApplicationContext
/public/info
  anonymous -> 200 open to everyone
  ann       -> 200 open to everyone
  root      -> 200 open to everyone
/api/orders
  anonymous -> 401
  ann       -> 200 orders
  root      -> 200 orders
/admin/stats
  anonymous -> 401
  ann       -> 403
  root      -> 200 stats
  • The context class is AnnotationConfigReactiveWebServerApplicationContext: Spring Boot detected WebFlux and started Reactor Netty, not Tomcat.
  • /public/info answered 200 for everyone, because of permitAll().
  • /api/orders gave 401 to the anonymous client and 200 to both users, because of anyExchange().authenticated().
  • /admin/stats gave 401 to the anonymous client, 403 to ann, who has only ROLE_USER, and 200 to root.

As with the servlet DSL, rules are checked top to bottom and the first match wins, so specific paths go first. MapReactiveUserDetailsService is the reactive in-memory user store. @EnableWebFluxSecurity is optional in a Spring Boot application, which applies it by itself; it is shown here because a plain Spring WebFlux application needs it. Note also that the chain is returned with http.build() and the method declares no checked exception, unlike the servlet HttpSecurity.

The reactive security context

Getting the current user is where most code ported from Spring MVC breaks. This controller asks for the user four ways in one request, including one that hops to another thread pool, and the old ThreadLocal way:

Java
package demo.reactive.context;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public class ReactiveContext {

    static String threadLocalUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth == null ? "null" : auth.getName();
    }

    static Mono<String> reactiveUser() {
        return ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getName)
                .defaultIfEmpty("empty");
    }

    @RestController
    static class MeController {
        @GetMapping("/me")
        Mono<String> me(Mono<Authentication> parameter) {
            String fromThreadLocal = threadLocalUser();
            return parameter.map(Authentication::getName)
                    .zipWith(reactiveUser())
                    .zipWith(reactiveUser().publishOn(Schedulers.parallel()))
                    .map(t -> "Mono<Authentication> parameter          = " + t.getT1().getT1()
                            + "\n  ReactiveSecurityContextHolder            = " + t.getT1().getT2()
                            + "\n  ReactiveSecurityContextHolder, parallel  = " + t.getT2()
                            + "\n  SecurityContextHolder (ThreadLocal)      = " + fromThreadLocal);
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(MeController.class)
    static class App {
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.user.name", "ann", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            HttpResponse<String> r = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create(base + "/me"))
                            .header("Authorization", "Basic "
                                    + Base64.getEncoder().encodeToString("ann:pw".getBytes()))
                            .build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("GET /me as ann -> " + r.statusCode());
            System.out.println("  " + r.body());
        }
    }
}
Output
GET /me as ann -> 200
  Mono<Authentication> parameter          = ann
  ReactiveSecurityContextHolder            = ann
  ReactiveSecurityContextHolder, parallel  = ann
  SecurityContextHolder (ThreadLocal)      = null
  • A Mono<Authentication> controller parameter gave ann.
  • ReactiveSecurityContextHolder.getContext() gave ann too. It returns a Mono that reads the security context from the Reactor Context of the subscription, where the security filter put it.
  • After publishOn(Schedulers.parallel()), which moved the work to another thread, the answer was still ann. The Reactor Context belongs to the subscription, not to a thread, so it travels with the data.
  • SecurityContextHolder, the ThreadLocal used in Spring MVC, returned null. Nothing went wrong: it is simply never set in a WebFlux application, and code that reads it, including libraries written for the servlet stack, sees no user.

The Reactor Context is filled when the response is subscribed to, and it flows upstream to everything inside that chain. A Mono created and subscribed to separately, for example with block() in a helper or a subscribe() that starts a background task, does not get it. Keep all work that needs the user inside the chain returned by the controller. Since this application declares no SecurityWebFilterChain, it also shows Spring Boot's reactive default: HTTP Basic worked with the user from spring.security.user.*.

Reactive method security

@PreAuthorize and @PostFilter work on reactive methods too, but the checks become part of the returned Mono or Flux. This program calls a service directly, without a web server, and supplies the user through contextWrite, which is what the web filter does for a real request:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
// A wildcard keeps this import line under 100 characters (EnableReactiveMethodSecurity).
import org.springframework.security.config.annotation.method.configuration.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class ReactiveMethodSecurity {

    record Invoice(int id, String owner) {
    }

    static class InvoiceService {
        @PreAuthorize("hasRole('ADMIN')")
        public Mono<String> purge() {
            return Mono.fromSupplier(() -> "purged");
        }

        @PostFilter("filterObject.owner == authentication.name")
        public Flux<Invoice> all() {
            return Flux.range(1, 6).map(i -> new Invoice(i, i % 3 == 0 ? "ann" : "bob"));
        }

        @PreAuthorize("hasRole('ADMIN')")
        public String blockingPurge() {
            return "purged without a Publisher";
        }
    }

    @Configuration
    @EnableReactiveMethodSecurity
    static class Config {
        @Bean
        InvoiceService invoiceService() {
            return new InvoiceService();
        }
    }

    static Authentication user(String name, String role) {
        return UsernamePasswordAuthenticationToken.authenticated(name, null,
                AuthorityUtils.createAuthorityList(role));
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            InvoiceService service = context.getBean(InvoiceService.class);
            Authentication ann = user("ann", "ROLE_USER");
            Authentication root = user("root", "ROLE_ADMIN");

            System.out.println("purge() as ann : " + service.purge()
                    .contextWrite(ReactiveSecurityContextHolder.withAuthentication(ann))
                    .onErrorResume(e -> Mono.just(e.getClass().getSimpleName()))
                    .block());
            System.out.println("purge() as root: " + service.purge()
                    .contextWrite(ReactiveSecurityContextHolder.withAuthentication(root))
                    .block());
            System.out.println("purge() with no context: " + service.purge()
                    .onErrorResume(e -> Mono.just(e.getClass().getSimpleName()))
                    .block());

            Mono<String> notSubscribed = service.purge();
            System.out.println("purge() called but not subscribed: returned a Mono: "
                    + (notSubscribed instanceof Mono) + ", nothing has run yet");

            System.out.println("all() as ann: " + service.all()
                    .contextWrite(ReactiveSecurityContextHolder.withAuthentication(ann))
                    .collectList().block());

            try {
                service.blockingPurge();
            } catch (RuntimeException e) {
                String message = e.getMessage();
                System.out.println("blockingPurge(): " + e.getClass().getSimpleName() + ":");
                System.out.println("  " + message.substring(message.indexOf("must return"),
                        message.indexOf(" (for example")));
            }
        }
    }
}
Output
purge() as ann : AuthorizationDeniedException
purge() as root: purged
purge() with no context: AuthorizationDeniedException
purge() called but not subscribed: returned a Mono: true, nothing has run yet
all() as ann: [Invoice[id=3, owner=ann], Invoice[id=6, owner=ann]]
blockingPurge(): IllegalStateException:
  must return an instance of org.reactivestreams.Publisher
  • purge() as ann produced an AuthorizationDeniedException as an error signal in the Mono, not as an exception thrown by the call, so the program handled it with onErrorResume.
  • As root, with ROLE_ADMIN, the same call emitted purged.
  • With no security context at all, the check failed with the same exception.
  • Calling purge() without subscribing returned a Mono and ran nothing: the permission check, like the method's work, happens at subscription time.
  • @PostFilter on a Flux filtered element by element and kept invoices 3 and 6, the ones owned by ann.
  • blockingPurge(), which returns a plain String, failed with IllegalStateException: under @EnableReactiveMethodSecurity, a secured method must return a Publisher (or be a Kotlin coroutine).

The lazy check has a practical consequence: ReactiveSecurityContextHolder.withAuthentication(...) must be applied to the chain that subscribes, as here with contextWrite. Setting a ThreadLocal context before the call, as in servlet tests, has no effect. The limits of all Spring proxies apply as well: calls on this and on private or final methods are not checked, as the method security page shows.

A reactive JWT resource server

Bearer tokens fit WebFlux well, because checking a JWT needs no session and no blocking lookup. This application uses oauth2ResourceServer().jwt() with a ReactiveJwtDecoder and calls one endpoint with four tokens:

Java
package demo.reactive.jwt;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

public class ReactiveJwt {

    static final SecretKey KEY = new SecretKeySpec(
            "a-32-byte-secret-for-hs256-demo!".getBytes(StandardCharsets.UTF_8), "HmacSHA256");

    @RestController
    static class OrderController {
        @GetMapping("/api/orders")
        Mono<String> list(@AuthenticationPrincipal Jwt jwt) {
            return Mono.just("orders of " + jwt.getSubject());
        }

        @PostMapping("/api/orders")
        Mono<String> create() {
            return Mono.just("order created");
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(OrderController.class)
    static class App {
        @Bean
        SecurityWebFilterChain security(ServerHttpSecurity http) {
            return http
                    .authorizeExchange(ex -> ex
                            .pathMatchers(HttpMethod.POST, "/api/**")
                            .hasAuthority("SCOPE_orders.write")
                            .anyExchange().hasAuthority("SCOPE_orders.read"))
                    .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()))
                    .build();
        }

        @Bean
        ReactiveJwtDecoder jwtDecoder() {
            return NimbusReactiveJwtDecoder.withSecretKey(KEY).build();
        }
    }

    static String token(String scope) {
        return NimbusJwtEncoder.withSecretKey(KEY).build().encode(JwtEncoderParameters.from(
                JwsHeader.with(MacAlgorithm.HS256).build(),
                JwtClaimsSet.builder().subject("ann").claim("scope", scope)
                        .expiresAt(Instant.now().plusSeconds(300)).build())).getTokenValue();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            String[][] calls = {
                {"GET", null}, {"GET", "orders.read"}, {"POST", "orders.read"},
                {"POST", "orders.read orders.write"},
            };
            for (String[] call : calls) {
                HttpRequest.Builder request = HttpRequest.newBuilder(
                        URI.create(base + "/api/orders"))
                        .method(call[0], HttpRequest.BodyPublishers.noBody());
                if (call[1] != null) {
                    request.header("Authorization", "Bearer " + token(call[1]));
                }
                HttpResponse<String> r = HttpClient.newHttpClient()
                        .send(request.build(), HttpResponse.BodyHandlers.ofString());
                System.out.printf("%-4s scope %-26s -> %d %s%n", call[0],
                        call[1] == null ? "(no token)" : call[1], r.statusCode(),
                        r.statusCode() == 200 ? r.body()
                                : r.headers().firstValue("WWW-Authenticate").orElse("")
                                        .replaceAll(",? ?(error_uri|resource_metadata)=\"[^\"]*\"",
                                                ""));
            }
        }
    }
}
Output
GET  scope (no token)                 -> 401 Bearer
GET  scope orders.read                -> 200 orders of ann
POST scope orders.read                -> 403 Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."
POST scope orders.read orders.write   -> 200 order created
  • With no token, the response was 401 with WWW-Authenticate: Bearer.
  • A token with the scope orders.read was accepted for the GET and refused for the POST with 403 insufficient_scope, because the POST rule wants SCOPE_orders.write.
  • With both scopes, the POST succeeded. It needed no CSRF token: as on the servlet side, requests that carry a bearer token are excluded from CSRF protection.

NimbusReactiveJwtDecoder has the same builders as the servlet decoder (withSecretKey, withPublicKey, withJwkSetUri, withIssuerLocation), and the spring.security.oauth2.resourceserver.jwt.* properties create it for you, so the OAuth2 resource server and JWT refresh token pages apply here unchanged apart from the type names. To read tokens from a header of your own, the reactive equivalent of a custom filter is an AuthenticationWebFilter with a ServerAuthenticationConverter and a ReactiveAuthenticationManager, added with http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION).

Testing with WebTestClient

spring-security-test provides SecurityMockServerConfigurers to put a user, a JWT or a CSRF token on WebTestClient requests. This program runs six requests against an admin-only application, including the CSRF case that catches most first tests:

Java
package demo.reactive.tests;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.test.web.reactive.server.EntityExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

public class ReactiveTests {

    @RestController
    static class AdminController {
        @GetMapping("/admin/stats")
        Mono<String> stats(Authentication auth) {
            return Mono.just("stats for " + auth.getName());
        }

        @PostMapping("/admin/reindex")
        Mono<String> reindex() {
            return Mono.just("reindexed");
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(AdminController.class)
    static class App {
        @Bean
        SecurityWebFilterChain security(ServerHttpSecurity http) {
            return http
                    .authorizeExchange(ex -> ex.anyExchange().hasRole("ADMIN"))
                    .httpBasic(Customizer.withDefaults())
                    .build();
        }

        @Bean
        MapReactiveUserDetailsService users() {
            return new MapReactiveUserDetailsService(
                    User.withUsername("root").password("{noop}pw").roles("ADMIN").build());
        }
    }

    static void show(String label, WebTestClient.RequestHeadersSpec<?> request) {
        EntityExchangeResult<String> r = request.exchange().expectBody(String.class)
                .returnResult();
        System.out.println(label + " -> " + r.getStatus().value()
                + (r.getStatus().is2xxSuccessful() ? " " + r.getResponseBody() : ""));
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            WebTestClient client = WebTestClient.bindToApplicationContext(context)
                    .apply(SecurityMockServerConfigurers.springSecurity())
                    .configureClient().build();

            show("GET  no user", client.get().uri("/admin/stats"));
            show("GET  mockUser() (ROLE_USER)", client
                    .mutateWith(SecurityMockServerConfigurers.mockUser())
                    .get().uri("/admin/stats"));
            show("GET  mockUser(\"root\").roles(\"ADMIN\")", client
                    .mutateWith(SecurityMockServerConfigurers.mockUser("root").roles("ADMIN"))
                    .get().uri("/admin/stats"));
            show("POST as admin, no CSRF token", client
                    .mutateWith(SecurityMockServerConfigurers.mockUser("root").roles("ADMIN"))
                    .post().uri("/admin/reindex"));
            show("POST as admin, with csrf()", client
                    .mutateWith(SecurityMockServerConfigurers.mockUser("root").roles("ADMIN"))
                    .mutateWith(SecurityMockServerConfigurers.csrf())
                    .post().uri("/admin/reindex"));
            show("GET  real Basic credentials", client.get().uri("/admin/stats")
                    .headers(h -> h.setBasicAuth("root", "pw")));
        }
    }
}
Output
GET  no user -> 401
GET  mockUser() (ROLE_USER) -> 403
GET  mockUser("root").roles("ADMIN") -> 200 stats for root
POST as admin, no CSRF token -> 403
POST as admin, with csrf() -> 200 reindexed
GET  real Basic credentials -> 200 stats for root
  • Without a user, the request got 401.
  • mockUser() with its defaults is a user named user with ROLE_USER, so the admin rule gave 403.
  • mockUser("root").roles("ADMIN") got 200 and the name root, with no password check involved.
  • A POST as that admin got 403: CSRF protection is on by default in WebFlux too, and the mock user does not bypass it.
  • Adding mutateWith(csrf()) supplied a valid token, and the POST succeeded.
  • Real Basic credentials also worked, since the client goes through the full filter chain.

bindToApplicationContext(context).apply(springSecurity()) is what makes the mock users work; in a JUnit test, @SpringBootTest with @AutoConfigureWebTestClient sets the same up. For token-based APIs, mockJwt() plays the role of jwt() on the servlet side, with the same authorities(...) and jwt(...) customisers.

Traps when moving from Spring MVC

  • Blocking user lookups: a ReactiveUserDetailsService that calls JPA or JDBC directly blocks an event-loop thread, and a handful of slow logins can stall the whole server. Use a reactive driver such as R2DBC, or wrap the call in Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()).
  • ThreadLocal-based code: anything that reads SecurityContextHolder, including servlet-era libraries and logging filters, sees no user. Pass the user explicitly or read it from the reactive context.
  • Subscribing outside the request: calling subscribe() on a secured Mono to fire and forget loses the security context, and the call is denied or runs as nobody.
  • Mixing stacks: with both spring-boot-starter-webmvc and spring-boot-starter-webflux on the classpath, Spring Boot starts the servlet stack, and a SecurityWebFilterChain bean is never used. Check which context class starts, as the first program prints.
  • Password hashing on the event loop: BCrypt takes tens of milliseconds by design, and with HTTP Basic it runs on every request. Prefer tokens for APIs, so that the hash is checked once at login.

Choosing a reactive security setup

Reactive equivalents for common needs
NeedUse
URL rulesSecurityWebFilterChain with authorizeExchange and pathMatchers
Users in a databaseA ReactiveUserDetailsService backed by R2DBC or another non-blocking client
The current user in a serviceReactiveSecurityContextHolder.getContext() inside the request's chain
Checks on service methods@EnableReactiveMethodSecurity with methods returning Mono or Flux
APIs with tokens from an identity provideroauth2ResourceServer().jwt() with ReactiveJwtDecoder
A custom credential headerAuthenticationWebFilter with a ServerAuthenticationConverter
TestsWebTestClient with mockUser(), mockJwt() and csrf()

The concepts are the same as on the servlet side, so the other security pages apply once the names are translated; what changes is that the security context travels with the subscription instead of the thread. For CSRF and CORS, which WebFlux configures with http.csrf(...) and http.cors(...) in the same way, see CSRF and CORS.