Spring Boot-预检响应没有HTTP正常状态

我正在使用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和的一个bec

Spring Security

我还要提及我正在将Spring Boot与Jersey一起使用。

谢谢。

回答:

我能够这样解决这个问题:

@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();

}

以上是 Spring Boot-预检响应没有HTTP正常状态 的全部内容, 来源链接: utcz.com/qa/399277.html

回到顶部