在BDD测试中设置WebTestClient CSRF保护

问题描述 投票:0回答:1

使用WebTestClient的我的(黄瓜)BDD单元测试失败(使用403 Forbidden)。经过一些调试后,我确定这是因为CSRF检查失败了。但我的测试步骤似乎正在设置CSRF令牌。出了什么问题?如何为WebTestClient测试设置CSRF令牌?


我的测试场景:

  Scenario Outline: Login
    Given that player "<player>" exists with  password "<password>"
    And presenting a valid CSRF token
    When log in as "<player>" using password "<password>"
    Then program accepts the login

我的测试步骤代码(注意client.mutateWith(csrf())的存在):


@SpringBootTest(...)
@AutoConfigureWebTestClient
public class WebSteps {

   @Autowired
   private WebTestClient client;

...

   private WebTestClient.ResponseSpec response;

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client.mutateWith(csrf());
   }

   @When("log in as {string} using password {string}")
   public void log_in_as_using_password(final String player,
            final String password) {
      response = client.post().uri("/login")
               .contentType(MediaType.APPLICATION_FORM_URLENCODED)
               .body(BodyInserters.fromFormData("username", player)
                        .with("password", password))
               .exchange();
   }

   @Then("program accepts the login")
   public void program_accepts_the_login() {
      response.expectStatus().isFound().expectHeader().valueEquals("Location",
               "/");
   }

...
spring-webflux spring-test cucumber-jvm csrf-protection
1个回答
0
投票

尽管它的名字,mutateWith()方法并没有真正改变它的对象。相反,它返回一个已应用突变的新对象。因此,而不是写作

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client.mutateWith(csrf());
   }

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client = client.mutateWith(csrf());
   }
© www.soinside.com 2019 - 2024. All rights reserved.