ReactiveSecurityContextHolder provides access to the SecurityContext in reactive applications, where thread-local storage cannot safely represent execution across reactive publishers. Spring Security stores the authenticated Authentication in the reactive context after successful authentication. section 17.2
Reading authentication in a controller
A reactive endpoint can obtain the context, extract its Authentication, and build a response such as “Hello john” without receiving Mono<Authentication> as a method parameter. This is an alternative access pattern with the same behavior. section 17.2
Listing 17.4 Working with a ReactiveSecurityContextHolder
@RestController
public class HelloController {
@GetMapping("/hello")
public Mono<String> hello() {
Mono<String> message =
ReactiveSecurityContextHolder.getContext() #1
.map(ctx -> ctx.getAuthentication()) #2
.map(auth -> "Hello " + auth.getName()); #3
return message;
}
}
Use the annotated controller listing to trace getContext(), authentication extraction, and response construction. section 17.2
