首页 > 解决方案 > Spring WebFlux Security - 是否可以在 SecurityWebFilterChain 上为不同的资源配置多个 ServerAuthenticationEntryPoints

问题描述

我的 spring webflux 应用程序中有几个不同的 API,它们需要对失败的身份验证做出不同的响应。我正在尝试为每个 API 设置不同的 ServerAuthenticationEntryPoints 来处理这些情况。

我发现这个示例配置显示了如何为不同的资源配置不同的 AuthenticationWebFilter,这使您能够单独设置 ServerAuthenticationSuccessHandler 和 ServerAuthenticationFailureHandler,但是我不确定如何在没有完全独立的 SecurityWebFilterChains 的情况下配置不同的 ServerAuthenticationEntryPoints。

如果我必须配置单独的 SecurityWebFilterChains,我该怎么做?

我的 SecurityWebFilterChain 目前是这样配置的 - 不幸的是,您不能单独设置 exceptionHandling,并且第二次调用 authenticationEntryPoint 是先例:

@Bean
fun securityWebFilterChain(
    http: ServerHttpSecurity,
    userServerAuthenticationEntryPoint: ServerAuthenticationEntryPoint,
    userAuthenticationWebFilter: AuthenticationWebFilter,
    deviceServerAuthenticationEntryPoint: ServerAuthenticationEntryPoint,
    deviceAuthenticationWebFilter: AuthenticationWebFilter,
    serverSecurityContextRepository: ServerSecurityContextRepository,
    authenticationManager: ReactiveAuthenticationManager,
    serverAccessDeniedHandler: ServerAccessDeniedHandler
): SecurityWebFilterChain {
    http
        .addFilterAt(userAuthenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
        .exceptionHandling()
            .authenticationEntryPoint(userServerAuthenticationEntryPoint)
            .and()
        .authorizeExchange()
            .pathMatchers(GET, "/sign-in").permitAll()
            .pathMatchers("/authentication/**").permitAll()
            .pathMatchers(GET, "/landing").hasAnyAuthority("USER", "ADMIN")
            .pathMatchers("/user-api/**").hasAnyAuthority("USER", "ADMIN")

    http
        .addFilterAt(deviceAuthenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
        .exceptionHandling()
            .authenticationEntryPoint(deviceServerAuthenticationEntryPoint)
            .and()
        .authorizeExchange()
            .pathMatchers("/device-api/**").hasAuthority("DEVICE")

    // GLOBAL
    http
        .httpBasic().disable()
        .formLogin().disable()
        .csrf().disable()
        .cors().disable()
        .securityContextRepository(serverSecurityContextRepository)
        .authenticationManager(authenticationManager)
        .exceptionHandling()
            .accessDeniedHandler(serverAccessDeniedHandler)
            .and()
        .authorizeExchange()
            .pathMatchers(GET, "/webjars/**").permitAll()
            .pathMatchers(GET, "/assets/**").permitAll()
            .anyExchange().authenticated()

    return http.build()
}

标签: spring-bootkotlinspring-securityspring-webflux

解决方案


事实证明,默认的 ServerAuthenticationEntryPoint 是 DelegatingServerAuthenticationEntryPoint,它使您能够通过 ServerWebExchangeMatchers 配置哪个实际入口点负责任何给定的 ServerWebExchange。看到这个评论


推荐阅读