如何为Spring Webflux应用程序实现自定义Spring Security PreAuthentication场景?

时间:2018-04-09 14:23:24

标签: spring authentication spring-security spring-webflux pre-authentication

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

但是,我找不到将此解决方案迁移到反应方案的良好起点。任何人都可以指点我正确的方向来帮助我吗?

1 个答案:

答案 0 :(得分:0)

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

我无法访问由我的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);
    }
}

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