Spring boot - Ответ на предпечатную проверку не имеет статуса HTTP ok - PullRequest
0 голосов
/ 05 сентября 2018

Я создаю сеть с 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 с Джерси.

Спасибо.

1 Ответ

0 голосов
/ 07 сентября 2018

Я смог решить эту проблему следующим образом:

Моя 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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...