I'm trying to persist user in http session and verify authentication request inside Gateway by using a custom filter. I found a similar question too:
SecurityConfig:
@Configuration
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(
ServerHttpSecurity http,
MyAuthenticationFilter myAuthenticationFilter
) {
http
.csrf()
.disable()
.authorizeExchange()
.pathMatchers("/**")
.permitAll()
.and()
.addFilterAt(myAuthenticationFilter, SecurityWebFiltersOrder.FIRST); // custom filter
return http.build();
}
MyAuthenticationFilter:
@Component
public class MyAuthenticationFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
exchange.getSession().map(
session -> {
session.getAttributes().put("userId", "id123");
// It does not print anything
System.out.println("userId in session: " + session.getAttribute("userId"));
return session;
}
);
return chain.filter(exchange);
}
}
By adding a custom filter, and attempting to read/write session attribute, as I observed in debug mode, the function inside map()
never gets executed, and nothing gets print out in the terminal. (Unsurprisingly, downstream service cannot read userId
from session even though both gateway and service share the same session).
Why is it not working? Here's a minimal reproduced version: Github repo, please take a look.