我正在使用Angular 5制作网站,每次尝试执行GET请求时都会遇到此错误。我在这里读了无数的答案,但没有一个对我有用。
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和的一个bec Spring Security。
CORS
OPTIONS
headers
Spring Security
我还要提及我正在将Spring Boot与Jersey一起使用。
谢谢。
我能够这样解决这个问题:
我的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(); }