Вы можете сделать это, но не уверены, что это будет работать или нет:
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return ReactiveSecurityContextHolder.getContext()
.flatMap(securityContext -> {
return authenticationManager.authenticate(new ReactiveServiceAuthentication(principal, authorization))
.map(authentication -> {
securityContext.setAuthentication(authentication);
return securityContext;
}).thenReturn("")
})
.defaultIfEmpty("")
.flatMap(string -> chain.filter(exchange));
}
Но лучший способ, которым я думаю, это. для этого вам понадобится дополнительный класс.
Класс SecurityConfig для создания класса Bean
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
private final ReactiveAuthenticationManager authenticationManager;
private final CustomSecurityContext customSecurityContext;
public SecurityConfig(ReactiveAuthenticationManager authenticationManager,
CustomSecurityContext customSecurityContext) {
this.authenticationManager = authenticationManager;
this.customSecurityContext = customSecurityContext;
}
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.cors().disable()
.formLogin().disable()
.httpBasic().disable()
.exceptionHandling()
.and()
.authenticationManager(authenticationManager)
.securityContextRepository(customSecurityContext)
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.build();
}
}
CustomSecurityCOntext
@Component
public class CustomSecurityContext implements ServerSecurityContextRepository {
private final AuthenticationManager authenticationManager;
public CustomSecurityContext(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
if (CHECK SOMETHING IF YOU WANT TO OTHERWISE NO NEED OF THIS IF) {
return authenticationManager.authenticate(new ReactiveServiceAuthentication(principal, authorization))
.map(SecurityContextImpl::new);
}
return Mono.empty();
}
}
А теперь в вашем классе ReactiveServiceAuthenticationFilter
@Component
public class ReactiveServiceAuthenticationFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return ReactiveSecurityContextHolder.getContext()
.map(securityContext -> (String) securityContext.getAuthentication().getPrincipal())
.defaultIfEmpty("")
.flatMap(principal -> {
if (!principal.isEmpty())
return chain.filter(decorate(exchange, principal));
// In decorate method check your authentication.
// If not valid then return mono error.
// Otherwise return ServerWebExchange object.
else
return chain.filter(exchange);
});
}
}