【问题标题】:How to solve CORS policy for HTTP status not ok?如何解决 HTTP 状态的 CORS 策略不正确?
【发布时间】:2020-09-15 22:37:03
【问题描述】:

我收到以下错误:

Access to fetch at 'http://localhost:8080/users/find-all/0' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我知道有很多这类问题,但我就是无法解决问题。 后端使用 Spring Boot 构建,前端基于 ReactJS。

@GetMapping("/find-all/{page}")
public PaginatedResultDto<UserDto> findAllPaginated(@PathVariable("page") int page, @RequestParam(defaultValue = NUMBER_OF_ELEMENTS) int numberOfElements) {
    Pageable pageable = PageRequest.of(page, numberOfElements);
    return getBaseFacade().findAllPaginated(pageable);
}

还有

getPaginatedResults = (pageIndex, resultsPerPage, endpoint, jwt) => {
    const resultsPerPagePath = resultsPerPage !== undefined ? "?numberOfElements=" + resultsPerPage : "";
    const endpointPath = BASE_URL + "/" + endpoint + "/find-all/" + pageIndex + resultsPerPagePath;
    return fetch(endpointPath, {
        method: "GET",
        headers: new Headers({
            "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
            "Authorization": "Bearer " + jwt
        })
    }).then( .. some error handling here )

我是这样配置WebSecurityConfigurerAdapter的:

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/users/login").permitAll()
            .antMatchers("/users/find-all/*").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

我也有一个WebMvcConfigurer

public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("Authorization", "Content-Type");
}

但我就是无法解决这个问题。我已经尝试了堆栈溢出的所有解决方案,但都没有奏效。

【问题讨论】:

  • 不相关,但在 client 中设置 COR 标头完全没有意义。它说它没有得到一个 OK,检查你的请求和响应数据。
  • 是这个资源服务器、授权服务器还是只是没有任何访问权限的服务器——意味着所有 api 都可以公开访问
  • @DaveNewton 我在浏览器控制台中登录时收到“TypeError:无法获取”响应。该请求正在与邮递员合作。
  • baeldung.com/spring-security-cors-preflight 您可能会在飞行前遇到身份验证错误。
  • @DaveNewton 非常感谢。这解决了我的问题 :) 祝你有美好的一天!

标签: java reactjs spring spring-boot cors


【解决方案1】:

你必须创建CorsConfigurationSource bean,示例如下:

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080",
                "http://localhost:4200",
                "https://localhost:4200"
                )
        );
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT", "OPTIONS"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(
                Arrays.asList(
                        "Access-Control-Allow-Headers",
                        "Access-Control-Allow-Origin",
                        "Access-Control-Request-Method",
                        "Access-Control-Request-Headers",
                        "Origin", "Cache-Control",
                        "Content-Type",
                        "Authorization"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

稍后在*[Web/Resource]ServerConfigurerAdapter添加以下代码

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
         ...// Please complete this line to compile
    }

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 2021-07-03
    • 2021-07-14
    • 2020-04-09
    • 2019-08-21
    • 2014-08-18
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多