【问题标题】:In what package is now located the .csrf() method in Spring 5?Spring 5 中的 .csrf() 方法现在位于哪个包中?
【发布时间】:2021-11-09 15:40:17
【问题描述】:

我正在尝试编写 IT。

mockMvc.perform( post( "/my_endpoint" )
            .contentType( MediaType.APPLICATION_JSON )
            .header("Authorization", my_credentials)
            .with(csrf())
            .content( jsonPayload )
                )
            .andExpect( status().isOk() );

我需要导入csrf()静态方法,但是通常创建的包(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors...)不再存在。

关于如何编写 csrf 保护以避免在测试中出现403 的一些新想法?

谢谢。

【问题讨论】:

    标签: spring spring-boot integration-testing csrf


    【解决方案1】:

    要使用 Spring Security 测试支持,您必须包含 spring-security-test-5.1.2.RELEASE.jar 作为项目的依赖项。 并在下面试一试:-

    import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProce ssors.*;
    
    mvc.perform(post("/").with(csrf()))
    

    或者,

    mvc.perform(post("/").with(csrf().asHeader()))
    

    或者,

    mvc.perform(post("/").with(csrf().useInvalidToken()))
    

    【讨论】:

    • 安全下的包测试不存在了,就是这个问题
    【解决方案2】:

    你可以如下使用它

    csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    

    【讨论】:

      【解决方案3】:

      我的回答是基于 Spring Reactive。 Spring Boot:2.6.1

      在 build.gradle 中添加以下条目

      testImplementation 'org.springframework.security:spring-security-test'
      

      然后,csrf() 方法将从下面的 import 中可用

      import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
      

      【讨论】:

        猜你喜欢
        • 2016-03-26
        • 1970-01-01
        • 2019-10-21
        • 2017-06-17
        • 2017-09-20
        • 2014-06-29
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        相关资源
        最近更新 更多