I am using Spring Cloud Gateway and Spring Security in a Spring Boot project (version 2.2.6). I have a custom Pre filter which needs to add headers to the request before it forwards the request to the downstream services. The Pre filter needs to read Spring Security's Authentication object to get the authorities before it can add the headers (it needs to do some lookup based on the authorities). Since Spring Cloud Gateway is reactive, I cannot use the static SecurityContextHolder class. Referencing this Stackoverflow question ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works, I tried the following in my custom Pre filter:
ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block()
As the OP posted, it does not work and it returns null. There were some suggestions about creating a custom filter in that stackoverflow issue. But I have not tried it as I want to access the Authentication object from the custom filter. Is there no direct way to get the Authentication object in the Spring Cloud Gateway custom filter?
Thanks