【问题标题】:How can I write Security tests for Spring Boot WebSocket endpoints如何为 Spring Boot WebSocket 端点编写安全测试
【发布时间】: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)
    }
}

但这有几个限制:

  1. 我们的OK 测试必须检查BAD_REQUEST 响应!
  2. 我们无法验证来自端点的任何实际负载。

所以它只适用于失败的场景。 Full source code for this example available on github.

【问题讨论】:

    标签: java spring spring-boot kotlin websocket


    【解决方案1】:

    我发现了一种基于我在 STOMP 测试中阅读的内容的方法,我意识到 STOMP 客户端使用的是普通的 WebSocket 客户端,并且我发现我能够在没有 STOMP 包装器的情况下以相同的方式构建测试。

    @Test
    @WithMockUser(authorities = ["SCOPE_read:client-ws"])
    fun `WebSocket authorized user is able to connect to endpoint`() {
        val latch = CountDownLatch(1)
        StandardWebSocketClient().execute(
            URI.create(String.format("ws://localhost:%d/protected-ws", port)),
            TestClientHandler(latch)
        ).subscribe()
        assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue()
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 2015-05-17
      • 2020-07-14
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2019-05-11
      • 2017-06-08
      • 2018-11-19
      相关资源
      最近更新 更多