Search code examples
spring-securityspring-webflux

How to get the "Authentication" Object with Spring WebFlux?


Using SpringMVC and Spring Security I can implement a Controller like this one (in Java):

@RestController
@RequestMapping("/auth")
class AuthController {
    private final AuthService authService;

    AuthController(AuthService authService) {
        this.authService = authService;
    }

    @GetMapping("/roles")
    Collection<String> findRoles(Authentication authentication) {
        final Object principal = authentication.getPrincipal();
        ...;
    }
}

But, how do I basically inject the object of org.springframework.security.core.Authentication in a handler class (or in a service class) when using Spring WebFlux and Spring Security (incl. the reactive parts)?


Solution

  • There are a lot of examples: https://github.com/spring-projects/spring-security

    This one shows how to get Principal in case of rest controller:

    https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebflux/src/main/java/sample/HelloUserController.java#L35

    And this one shows how to get Principal in case of webflux:

    https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebfluxfn/src/main/java/sample/HelloUserController.java#L37