【发布时间】:2018-09-07 18:37:43
【问题描述】:
问题:我没有让 Spring Security with Websockets 在 Webflux 项目中工作。
注意:我使用的是 Kotlin 而不是 Java。
依赖关系:
Spring Boot 2.0.0
Spring Security 5.0.3
Spring WebFlux 5.0.4
重要更新:我提出了一个 Spring 问题错误(3 月 30 日)here,其中一位 Spring 安全维护人员表示不支持,但他们可以为 Spring Security 5.1.0 M2 添加它。
链接: Add WebFlux WebSocket Support #5188
Webflux 安全配置
@EnableWebFluxSecurity
class SecurityConfig
{
@Bean
fun configure(http: ServerHttpSecurity): SecurityWebFilterChain
{
return http.authorizeExchange()
.pathMatchers("/").permitAll()
.anyExchange().authenticated()
.and().httpBasic()
.and().formLogin().disable().csrf().disable()
.build()
}
@Bean
fun userDetailsService(): MapReactiveUserDetailsService
{
val user = User.withDefaultPasswordEncoder()
.username("user")
.password("pass")
.roles("USER")
.build()
return MapReactiveUserDetailsService(user)
}
}
Webflux Websocket 配置
@Configuration
class ReactiveWebSocketConfiguration
{
@Bean
fun webSocketMapping(handler: WebSocketHandler): HandlerMapping
{
val map = mapOf(Pair("/event", handler))
val mapping = SimpleUrlHandlerMapping()
mapping.order = -1
mapping.urlMap = map
return mapping
}
@Bean
fun handlerAdapter() = WebSocketHandlerAdapter()
@Bean
fun websocketHandler() = WebSocketHandler { session ->
// Should print authenticated principal BUT does show NULL
println("${session.handshakeInfo.principal.block()}")
// Just for testing we send hello world to the client
session.send(Mono.just(session.textMessage("hello world")))
}
}
客户端代码
// Lets create a websocket and pass Basic Auth to it
new WebSocket("ws://user:pass@localhost:8000/event");
// ...
观察
在 websocket 处理程序中,主体显示 null
客户端无需经过身份验证即可连接。如果我在没有基本身份验证的情况下使用
WebSocket("ws://localhost:8000/event"),它仍然可以工作!所以 Spring Security 不会验证任何东西。
我错过了什么? 我做错了什么?
【问题讨论】:
-
我也有同样的问题。有什么帮助吗??
-
我们必须等到 Spring Security 团队实现了该功能(基于 Websockets 的基本身份验证)。但是,如果您等不及,则必须更改身份验证机制。
-
加上问题或添加 cmets 让 Rob Winch 知道这个问题很重要 :)
标签: spring-security websocket spring-webflux