【问题标题】:Spring Boot API returns 403 Forbidden as response to React AppSpring Boot API 返回 403 Forbidden 作为对 React App 的响应
【发布时间】: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


    【解决方案1】:

    抱歉,但是当我发出此端点时:

    @RequestMapping("/token")
    public CsrfToken csrf(CsrfToken token) {
        return token;
    }
    

    在simple-spring-starter(显示安全配置)中,我得到:

    java.lang.IllegalStateException: No primary or single unique constructor found for interface org.springframework.security.web.server.csrf.CsrfToken
    ...
    

    为了达到预期,我认为,足以:

    @RestController
    public class TokenController {
    
        @GetMapping("/token")
        public String csrf() {
            return "";
        }
       ...
    

    ...请澄清这个误解,然后我们也可以(肯定)做 POST。


    在客户端...,我认为,the name (of header) is X-XSRF-TOKEN (or parameter _csrf) ..在本章节和父章节中,我们可以找到更多信息/示例/注意事项。


    生产注意事项:

    当然,您应该将此类(/类型)端点保留为不受保护的端点。

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2013-07-23
      相关资源
      最近更新 更多