0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Spring WebFlux】WebTestClientで認証を迂回してテストを行う

Posted at

TL;DR

  • SecurityMockServerConfigurersに定義されたMutatorWebTestClientにセットすることで認証を迂回できる
    • 少なくとも記事にまとめたやり方ではパス・メソッド・Authority周りのチェックは迂回できない(逆に言うと、それらの設定に関してテストを行うことができる)

注意書き

最小構成でのチェックはできておらず、あくまで自分の環境での実装例であることにご注意ください。
また、org.springframework.security:spring-security-testは導入されている前提で書きます。

サンプルコードはKotlinで記述しますが、基本的な部分は変わらないはずです。

やること

WebTestClientを利用したテストを実装する際に、JWT認証をスキップします。
ここではSecurityMockServerConfigurers.JwtMutatorを設定するやり方を紹介します。
サンプルコードはJWTベースで書きますが、SecurityMockServerConfigurersドキュメントを見る限りOAuth2OIDCなども同じようなやり方で対応できそうでした。

サンプルコード

サンプルコードは以下の通りです。
注意点として、この書き方では、pathMatchersで設定するような、パス・メソッド・Authority周りのチェックは迂回できません(逆に言うと、それらの設定に関してテストを行うことができます)。

import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers
import org.springframework.test.web.reactive.server.WebTestClient

@SpringBootTest
@AutoConfigureWebTestClient
class FooTest @Autowired constructor(
    val baseClient: WebTestClient
) {
    // Authorityが設定されたWebTestClientを返す関数
    private fun WebTestClient.toAuthoritiesAwareClient(vararg authorities: String): WebTestClient {
        val mutator: SecurityMockServerConfigurers.JwtMutator = SecurityMockServerConfigurers.mockJwt()
            .authorities(authorities.map { GrantedAuthority { it } }) // 権限を設定

        return this.mutate()
            .apply(mutator)
            .build()
    }

    @Test
    fun test() {
        val client: WebTestClient = baseClient.toAuthoritiesAwareClient(/* 設定したいAuthorityを記述 */)

        // 通常同様にWebTestClientを使ったテストを記述
        val result = client.get()...

    }
}

呼び出し結果のステータスコードに関する補足

自分の環境では以下のようになりました。
割と当たり前の結果だと思いますが、これによってパス・権限周りのテストを行うことができました。

  • JWT認証を突破できない -> UNAUTHORIZED
  • 権限不足 -> FORBIDDEN
  • どちらもOK -> APIの実行結果に応じたステータス
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?