在WebFlux中添加AuthenticationWebFilter

时间:2018-10-04 17:55:04

标签: spring-security kotlin spring-webflux

我有一个使用Spring Webflux的功能端点定义的简单REST API,我正在尝试使用Spring Security进行保护。我试图添加一个AuthenticationWebFilter,该最终将包含用于验证请求的自定义逻辑。我当前的实现始终返回403。我已验证authentication.isAuthenticated()返回true。为什么对GET /message的请求未得到授权?

@SpringBootApplication
@EnableWebFluxSecurity
class SecurityApplication {
    @Bean
    fun routes() = router {
        GET("/message") { _ -> ServerResponse.ok().syncBody("Super secret message") }
    }

    @Bean
    fun configureSecurity(httpSecurity: ServerHttpSecurity): SecurityWebFilterChain {
        return httpSecurity
                .httpBasic().disable()
                .addFilterAt(authenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION).authorizeExchange().and().build()
    }
}

fun main(args: Array<String>) {
    runApplication<SecurityApplication>(*args)
}

fun authenticationFilter(): AuthenticationWebFilter {
    val authenticationWebFilter = AuthenticationWebFilter { authentication -> Mono.just(authentication) }


    authenticationWebFilter.setServerAuthenticationConverter { _ ->
        val authentication = UsernamePasswordAuthenticationToken("user", "user", listOf())
        Mono.just(authentication)
    }

    authenticationWebFilter.setRequiresAuthenticationMatcher(ServerWebExchangeMatchers.pathMatchers("/**"))

    return authenticationWebFilter
}

0 个答案:

没有答案