Как решить проблему политики CORS для статуса HTTP? - PullRequest
0 голосов
/ 28 мая 2020

Я получаю следующую ошибку:

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.

Я знаю, что есть много вопросов такого типа, но я просто не могу решить проблему. Бэкэнд построен с пружинной загрузкой, а интерфейс основан на 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");
}

Но я просто не могу решить эту проблему ... Я пробовал все решения от переполнения стека, но это не сработало.

1 Ответ

0 голосов
/ 28 мая 2020

Вы должны создать 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
    }
...