【发布时间】:2022-10-04 23:19:27
【问题描述】:
我正在尝试让我的 CSRF 正常工作。我有一个具有后控制器方法的 Spring Boot API,我试图在发送 CSRF-Token 以使其工作时调用它,但我得到的只是 403 Forbidden 响应。
弹簧引导控制器:
@RequestMapping("/token")
public CsrfToken csrf(CsrfToken token){
return token;
}
@PostMapping(value = "/postendpoint")
public ResponseEntity<?> somePost(String text){
return ResponseEntity
.ok()
.header("Access-Control-Allow-Origin", "http://localhost:3000")
.body(text);
}
配置类:
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and().cors();
return http.build();
}
}
来自 React 的请求:
response = await axios.get('http://127.0.0.1:8080/tasks/token', {withCredentials: true}).then((tokenResp) => {
console.log(tokenResp);
return axios.post('http://127.0.0.1:8080/tasks/postendpoint',
{
withCredentials: true,
headers: {
'X-CSRF-TOKEN': tokenResp.data.token
}
}
);
}).then((res) => console.log(res));
【问题讨论】:
标签: java reactjs spring-boot