Spring Secure配置csrf之后,原本可用的URL返回404错误

发布于 2022-09-07 20:21:28 字数 3786 浏览 25 评论 0

继承WebSecurityConfigurerAdapter 的实现如下。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("USER")
                .and()
                .formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
                .usernameParameter("username").passwordParameter("password")
                .and()
                .logout().logoutSuccessUrl("/login?logout")
                .and()
                .exceptionHandling().accessDeniedPage("/403")
                .and()
                .csrf();
    }

区别在与最后一行,如果是csrf().disable()则一切正常,去掉disable()报404错误
测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CSVImportIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private StorageService storageService;

    @LocalServerPort
    private int port;

    @Test
    public void shouldUploadFile() {
        ClassPathResource resource = new ClassPathResource("testUpload.txt", getClass());

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("file", resource);
        ResponseEntity<String> response = restTemplate.postForEntity("/", map, String.class);

        assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.FOUND);
        assertThat(response.getHeaders().getLocation().toString()).startsWith("http://localhost:" + this.port + "/");
        then(storageService).should().store(any(MultipartFile.class));
    }
}

一般在assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.FOUND);这行报错

    tractDirtiesContextTestExecutionListener : After test method: context  
 [DefaultTestContext@3899782c testClass = CSVImportIT, testInstance = dems.CSVImportIT@6d514259,  
 testMethod = shouldUploadFile@CSVImportIT, testException = org.junit.ComparisonFailure:  
 expected:<[302]> but was:<[404]>, mergedContextConfiguration =  
 [WebMergedContextConfiguration@1603cd68 testClass = CSVImportIT, locations = '{}', classes = 
  '{class dems.Application}', contextInitializerClasses = '[]', activeProfiles = '{}',  
 propertySourceLocations = '{}', propertySourceProperties =  
 '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, 
  server.port=0}', contextCustomizers =  
 set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5fa07e12,  
 org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@366647c2,  
 org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@a9a8d3f1, 
  org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@2bfc268b, 
 org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0,  
 org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@550ee7e5], resourceBasePath = 'src/main/webapp', contextLoader =  
 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes =  
 map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' ->  
 false]], class annotated with @DirtiesContext [false] with mode [null], method annotated with 
  @DirtiesContext [false] with mode [null].   

在Controller对应URL的Mapping方法里加断点,debug发现没有命中断点就报错了。把disable()加回去又正常了。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文