mem*_*und 6 spring spring-security spring-test spring-boot
为什么我会收到403 FORBIDDEN以下测试的分数?
@RestController
public class MyServlet {
@PostMapping("/")
public Mono<String> accept(Authentication authentication) {}
}
@WebFluxTest(MyServlet.class)
@WithMockUser
public class MyServletTest {
@Autowired
private WebTestClient webClient;
@Test
public void test() {
webClient.post().url("/")
.exchange()
.expectStatus().isOk();
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
java.lang.AssertionError: Status expected:<200 OK> but was:<403 FORBIDDEN>
> POST /
> WebTestClient-Request-Id: [1]
> Content-Type: [application/json]
No content
< 403 FORBIDDEN Forbidden
< Content-Type: [text/plain]
< Cache-Control: [no-cache, no-store, max-age=0, must-revalidate]
< Pragma: [no-cache]
< Expires: [0]
< X-Content-Type-Options: [nosniff]
< X-Frame-Options: [DENY]
< X-XSS-Protection: [1 ; mode=block]
< Referrer-Policy: [no-referrer]
CSRF Token has been associated to this client
Run Code Online (Sandbox Code Playgroud)
据我所知,@WebFluxTest禁用 csrf。那它为什么抱怨呢?
webClient.mutateWith(csrf()).post()...;
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为您spring-boot-starter-security的类路径中可能有。您需要创建一个配置:
@Configuration
@EnableWebFluxSecurity
public class WebFluxSecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http.csrf().disable().build();
}
}
Run Code Online (Sandbox Code Playgroud)
并将其导入到您的测试中
@Import(WebFluxSecurityConfig.class)
Run Code Online (Sandbox Code Playgroud)
显然,默认情况下没有在@WebFluxTest.
我在这里找到了解决方案:https : //github.com/spring-projects/spring-boot/issues/16088
| 归档时间: |
|
| 查看次数: |
1540 次 |
| 最近记录: |