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

Viewed 7050

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)?

2 Answers
//@AuthenticationPrincipal Mono<UserLogin> principal
//@AuthenticationPrincipal Mono<Authentication> principal

@GetMapping("/me")
public Mono<Map<String, Object>> current(@AuthenticationPrincipal Mono<Principal> principal) {
    return principal
            .map(user ->
                    Map.of(
                            "name", user.getName(),
                            "roles", AuthorityUtils.authorityListToSet(((Authentication) user)
                                    .getAuthorities())
                    )
            );
}

You can also use :

 ReactiveSecurityContextHolder.getContext()
            .map(m->m.getAuthentication())
            .map(m->m.getPrincipal());
Related