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 ThreadLocalThreadLocal
Spring Security therefore has a reactive counterpart for every servlet piece:
| Purpose | Spring MVC (servlet) | WebFlux (reactive) |
|---|---|---|
| Filter chain bean | SecurityFilterChain | SecurityWebFilterChain |
| Configuration DSL | HttpSecurityauthorizeHttpRequestsrequestMatchersanyRequest | ServerHttpSecurityauthorizeExchangepathMatchersanyExchange |
| Enabling annotation | @EnableWebSecurity | @EnableWebFluxSecurity |
| Loading users | UserDetailsService | ReactiveUserDetailsServiceMono<UserDetails> |
| Checking credentials | AuthenticationManager | ReactiveAuthenticationManager |
| Current user | SecurityContextHolderThreadLocal | ReactiveSecurityContextHolderContext |
| Method security | @EnableMethodSecurity | @EnableReactiveMethodSecurityMonoFlux |
| JWT decoder | JwtDecoder | ReactiveJwtDecoder |
| Test client | MockMvc with SecurityMockMvcRequestPostProcessors | WebTestClientSecurityMockServerConfigurers |
Spring Boot chooses between the two from the classpath: with spring-boot-starter-webfluxjava.net.http.HttpClientWebTestClient
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
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));
}
}
}
}
}
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
: Spring Boot detected WebFlux and started Reactor Netty, not Tomcat.AnnotationConfigReactiveWebServerApplicationContext answered 200 for everyone, because of/public/info .permitAll() gave 401 to the anonymous client and 200 to both users, because of/api/orders .anyExchange().authenticated() gave 401 to the anonymous client, 403 to/admin/stats , who has onlyann , and 200 toROLE_USER .root
As with the servlet DSL, rules are checked top to bottom and the first match wins, so specific paths go first. MapReactiveUserDetailsService@EnableWebFluxSecurityhttp.build()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
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());
}
}
}
GET /me as ann -> 200
Mono<Authentication> parameter = ann
ReactiveSecurityContextHolder = ann
ReactiveSecurityContextHolder, parallel = ann
SecurityContextHolder (ThreadLocal) = null
- A
controller parameter gaveMono<Authentication> .ann gaveReactiveSecurityContextHolder.getContext() too. It returns aann that reads the security context from the ReactorMono of the subscription, where the security filter put it.Context- After
, which moved the work to another thread, the answer was stillpublishOn(Schedulers.parallel()) . The Reactorann belongs to the subscription, not to a thread, so it travels with the data.Context , theSecurityContextHolder used in Spring MVC, returnedThreadLocal . 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.null
The Reactor ContextMonoblock()subscribe()SecurityWebFilterChainspring.security.user.*
Reactive method security
@PreAuthorize@PostFilterMonoFluxcontextWrite
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")));
}
}
}
}
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
aspurge() produced anann as an error signal in theAuthorizationDeniedException , not as an exception thrown by the call, so the program handled it withMono .onErrorResume- As
, withroot , the same call emittedROLE_ADMIN .purged - With no security context at all, the check failed with the same exception.
- Calling
without subscribing returned apurge() and ran nothing: the permission check, like the method's work, happens at subscription time.Mono on a@PostFilter filtered element by element and kept invoices 3 and 6, the ones owned byFlux .ann , which returns a plainblockingPurge() , failed withString : underIllegalStateException , a secured method must return a@EnableReactiveMethodSecurity (or be a Kotlin coroutine).Publisher
The lazy check has a practical consequence: ReactiveSecurityContextHolder.withAuthentication(...)contextWriteThreadLocalthis
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()ReactiveJwtDecoder
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)=\"[^\"]*\"",
""));
}
}
}
}
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
was accepted for the GET and refused for the POST with 403orders.read , because the POST rule wantsinsufficient_scope .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.
NimbusReactiveJwtDecoderwithSecretKeywithPublicKeywithJwkSetUriwithIssuerLocationspring.security.oauth2.resourceserver.jwt.*AuthenticationWebFilterServerAuthenticationConverterReactiveAuthenticationManagerhttp.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION)
Testing with WebTestClient
spring-security-testSecurityMockServerConfigurersWebTestClient
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")));
}
}
}
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.
with its defaults is a user namedmockUser() withuser , so the admin rule gave 403.ROLE_USER got 200 and the namemockUser("root").roles("ADMIN") , with no password check involved.root- 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
supplied a valid token, and the POST succeeded.mutateWith(csrf()) - Real Basic credentials also worked, since the client goes through the full filter chain.
bindToApplicationContext(context).apply(springSecurity())@SpringBootTest@AutoConfigureWebTestClientmockJwt()jwt()authorities(...)jwt(...)
Traps when moving from Spring MVC
- Blocking user lookups: a
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 inReactiveUserDetailsService .Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) - ThreadLocal-based code: anything that reads
, including servlet-era libraries and logging filters, sees no user. Pass the user explicitly or read it from the reactive context.SecurityContextHolder - Subscribing outside the request: calling
on a securedsubscribe() to fire and forget loses the security context, and the call is denied or runs as nobody.Mono - Mixing stacks: with both
andspring-boot-starter-webmvc on the classpath, Spring Boot starts the servlet stack, and aspring-boot-starter-webflux bean is never used. Check which context class starts, as the first program prints.SecurityWebFilterChain - 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
| Need | Use |
|---|---|
| URL rules | SecurityWebFilterChainauthorizeExchangepathMatchers |
| Users in a database | A ReactiveUserDetailsService |
| The current user in a service | ReactiveSecurityContextHolder.getContext() |
| Checks on service methods | @EnableReactiveMethodSecurityMonoFlux |
| APIs with tokens from an identity provider | oauth2ResourceServer().jwt()ReactiveJwtDecoder |
| A custom credential header | AuthenticationWebFilterServerAuthenticationConverter |
| Tests | WebTestClientmockUser()mockJwt()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(...)http.cors(...)