【发布时间】:2021-01-08 09:38:10
【问题描述】:
我正在寻找一种明智的方法来对我们的 WebSocket 安全实现进行单元测试。我们使用 Spring TestRestTemplate 来测试我们的 REST 端点,似乎这种方法几乎适用于 WebSockets。如果您接受BAD_REQUEST 作为OK 的替代品。
有没有测试 Spring WebSockets 的好方法?
这是我们的处理程序映射
@Configuration
class HandlerMappingConfiguration {
@Bean
fun webSocketMapping(webSocketHandler: DefaultWebSocketHandler?): HandlerMapping {
val map: MutableMap<String, WebSocketHandler?> = HashMap()
map["/"] = webSocketHandler
map["/protected-ws"] = webSocketHandler
val handlerMapping = SimpleUrlHandlerMapping()
handlerMapping.order = 1
handlerMapping.urlMap = map
return handlerMapping
}
}
这是我们的安全配置
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
class SecurityConfig(
private val authenticationConverter: ServerAuthenticationConverter,
@param:Value("\${spring.security.oauth2.resourceserver.jwt.issuer-uri}") private val issuerUri: String,
@param:Value("\${spring.security.oauth2.resourceserver.jwt.audience}") private val audience: String
) {
@Bean
fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/protected-ws").hasAuthority("SCOPE_read:client-ws")
.pathMatchers("/protected").hasAuthority("SCOPE_read:client")
.matchers(EndpointRequest.toAnyEndpoint()).permitAll()
.anyExchange().authenticated()
.and()
.oauth2ResourceServer()
.bearerTokenConverter(authenticationConverter)
.jwt()
return http.build()
}
@Bean
open fun jwtDecoder(): ReactiveJwtDecoder {
val jwtDecoder = ReactiveJwtDecoders.fromOidcIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
jwtDecoder.setJwtValidator(DelegatingOAuth2TokenValidator(withIssuer(), audienceValidator()))
return jwtDecoder
}
private fun withIssuer(): OAuth2TokenValidator<Jwt>? {
return JwtValidators.createDefaultWithIssuer(
issuerUri
)
}
private fun audienceValidator(): OAuth2TokenValidator<Jwt> {
return JwtAudienceValidator(
audience
)
}
}
这是我们用于 REST 端点的 IntegrationTest 类
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RestSecurityTest(@Autowired val restTemplate: TestRestTemplate) {
@Test
fun `Unauthorized user is unauthorized`() {
val entity = restTemplate.getForEntity<String>("/world", String::class.java)
assertThat(entity.statusCode).isEqualTo(HttpStatus.UNAUTHORIZED)
}
@Test
@WithMockUser(authorities = ["SCOPE_read:world"])
fun `Authorized user, without required scope is Forbidden`() {
val entity = restTemplate.getForEntity<String>("/protected", String::class.java)
assertThat(entity.statusCode).isEqualTo(HttpStatus.FORBIDDEN)
}
@Test
@WithMockUser(authorities = ["SCOPE_read:client"])
fun `Authorized user, with required scope is OK`() {
val entity = restTemplate.getForEntity<String>("/protected", String::class.java)
assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
}
}
我们希望为我们的 WebSocket 端点实现类似的东西......例如
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebSocketSecurityTest(@Autowired val restTemplate: TestRestTemplate) {
@Test
fun `WebSocket unauthorized user is unauthorized`() {
val entity = restTemplate.getForEntity<String>("/protected-ws", String::class.java)
assertThat(entity.statusCode).isEqualTo(HttpStatus.UNAUTHORIZED)
}
@Test
@WithMockUser(authorities = ["SCOPE_read:world"])
fun `WebSocket authorized user, without required scope is forbidden`() {
val entity = restTemplate.getForEntity<String>("/protected-ws", String::class.java)
assertThat(entity.statusCode).isEqualTo(HttpStatus.FORBIDDEN)
}
@Test
@WithMockUser(authorities = ["SCOPE_read:client-ws"])
fun `WebSocket Authorized user, with required scope is OK`() {
val entity = restTemplate.getForEntity<String>("/protected-ws", String::class.java)
// You can't open a WebSocket connection with a REST client. But this shows the request is authorized.
assertThat(entity.statusCode).isEqualTo(HttpStatus.BAD_REQUEST)
}
}
但这有几个限制:
- 我们的
OK测试必须检查BAD_REQUEST响应! - 我们无法验证来自端点的任何实际负载。
所以它只适用于失败的场景。 Full source code for this example available on github.
【问题讨论】:
标签: java spring spring-boot kotlin websocket