I am using Spring MVC to create a service and Spring WebFlux to use WebClient. How can I propagate SecurityContext inside WebClient to access the login user that was set with SecurityContextHolder?
My configuration
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
Application properties
spring.reactor.context-propagation=auto
Setting user in SecurityContextHolder
SecurityContext context = SecurityContextHolder.createEmptyContext();
User user = new User("User", "", true, true, true, true, List.of());
Authentication authentication = new UsernamePasswordAuthenticationToken(user, "", List.of());
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
Creating WebClient, where I would like to set Authorization
header taken from login User class.
public WebClient webClient(WebClient.Builder webClientBuilder) {
WebClient webClient = webClientBuilder
.filter(securityExchangeFilter) // setting Authorization header
.build();
}
New contributor
user24670094 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.