Spring boot - ответ на предполетную проверку не имеет статуса HTTP ok

Я создаю сеть с помощью Angular 5 и получаю эту ошибку каждый раз, когда пытаюсь выполнить GET запрос. Я прочитал тонны ответов здесь, и ни один из них не работает на меня.

Насколько я читал, это потому, что я добавляю пользовательские заголовки к этому запросу, что необходимо сделать, потому что я использую Spring Security, которая, как мне кажется, вызывает проблему. Это моя текущая конфигурация Spring Security, которую я сделал после чтения вопросов, но все еще не работает, я не знаю, делаю ли я что-то в ней не так:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .authorizeRequests().anyRequest().permitAll()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
    }

    @Override
    public void configure(WebSecurity web ) throws Exception
    {
        web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Надеюсь, вы можете помочь, потому что я уже несколько дней борюсь с этим. Я думаю, очевидно, что проблема здесь CORS, мой GET запрос преобразуется в OPTIONS один из пользовательских headers и Spring Security.

Также я хотел бы упомянуть, что я использую Spring Boot с Jersey.

Спасибо.


person Wrong    schedule 05.09.2018    source источник


Ответы (2)


Мне удалось решить эту проблему так:

Моя WebMvcConfiguration:

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**");
    }

}

Моя конфигурация безопасности:

@Override
protected void configure(HttpSecurity http) throws Exception {
      http.cors().disable()
          .authorizeRequests()
          .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
          .anyRequest()
          .fullyAuthenticated()
          .and()
          .httpBasic()
          .and()
          .csrf().disable();
}
person Fabiano Góes    schedule 07.09.2018
comment
Здорово, что ты даешь ответы! Надеюсь, вы не против всего лишь нескольких указателей? Когда вы отвечаете, вы должны попытаться найти источники и объяснить, почему проблема возникла в первую очередь, как вы ее исправили и почему это работает. Это принесет вам намного больше репутации! Еще раз: это здорово, что вы на борту и пытаетесь помочь, и это только то, что я пытаюсь сделать! - person Andreas Storvik Strauman; 07.09.2018
comment
Что делает первый класс @fabiano? - person Wrong; 28.09.2018
comment
Эта строка исправила это для меня: .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() - person RiesvGeffen; 10.12.2018

Добавьте следующую конфигурацию,

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
                        .allowedHeaders("*");
            }
        };
    }
}
person Naveen Perera    schedule 29.08.2019