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

赫赫张
  • 250

继承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()加回去又正常了。

回复
阅读 3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏