liveBook · Manning

ReactiveSecurityContextHolder

As explained in Spring Security in Action, Second Edition

ReactiveSecurityContextHolder is the Spring Security holder that provides access to the security context through reactive execution context rather than thread-local storage.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains context access and post-authentication storage flow, but does not detail the holder’s internal implementation.
Examples
Demonstrates a HelloController that reads Authentication and returns “Hello john” from a reactive endpoint.
What it assumes
Uses reactive publishers and Mono-based authentication rather than plain Authentication values.
What you can do after
Apply it via Spring Security to read Authentication from a reactive SecurityContext in a controller.
How it connects
Connects ReactiveSecurityContextHolder with SecurityContext, Authentication, and reactive publishers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.