如何为 Spring Webflux 应用程序实现自定义的 Spring 安全预身份验证方案



为了使用 Webflux 实现基于 Spring MVC 的应用程序现代化,我需要更新我的自定义预身份验证方案。我已经使用 FilterBean s(如 https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#preauth 中所述(构建了一个很好的解决方案。

但是,我找不到将此解决方案迁移到反应方案的良好起点。谁能帮我指出正确的方向?

我处于同样的情况。尝试使用容器身份验证(preauth.j2ee Spring MVC中(,但尚未找到完整的解决方案。

我无法访问由我的 CAS 身份验证系统进行身份验证的java.security.PrincipalserverWebExchange.getPrincipal()都是空的。

由于您要求一个起点,这是我的配置:

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Slf4j
public class SecurityConfig {
@Bean
    public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
        return http
                .csrf().disable()
                .httpBasic().disable()
                .formLogin().disable()
                .logout().disable()
                .authenticationManager(this.authenticationManager())
                .securityContextRepository(this.securityContextRepository())
                .authorizeExchange().pathMatchers("/public/**").permitAll()
                .and().authorizeExchange().anyExchange().authenticated()
                .and().build();
    }
    @Bean
    ReactiveAuthenticationManager authenticationManager() {
        return authentication -> {
            log.debug("Autentication: " + authentication.toString());
            if (authentication instanceof CustomPreAuthenticationToken) {
                authentication.setAuthenticated(true);
            }
            return Mono.just(authentication);
        };
    }
    @Bean
    ServerSecurityContextRepository securityContextRepository() {
        return new ServerSecurityContextRepository() {
            @Override
            public Mono<Void> save(ServerWebExchange serverWebExchange, SecurityContext securityContext) {
                return null;
            }
            @Override
            public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
                return serverWebExchange.getPrincipal()
                        .defaultIfEmpty(() -> "empty principal")
                        .flatMap(principal -> Mono.just(new SecurityContextImpl(new CustomPreAuthenticationToken(principal.getName(), principal,  AuthorityUtils.createAuthorityList("ROLE_USER") ))));
            }
        };
    }
}

public class CustomPreAuthenticationToken extends UsernamePasswordAuthenticationToken {        
    public CustomPreAuthenticationToken(String key, Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(key, principal, authorities);
    }
}

希望这里有人能完成这个答案。

最新更新