【发布时间】:2020-11-09 23:20:15
【问题描述】:
我在 StackOverflow 上看到了很多关于这个主题的其他问题,但没有解决我的问题。
我在localhost 端口8000 上使用SpringBoot 开发了一个rest API。我正在尝试从浏览器的fetch API 向端点发出请求。我还使用以下 bean 启用了 CORS:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedHeaders("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.allowedHeaders("*");
}
};
}
这是我的安全配置:
@EnableWebSecurity
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired private UserService userService;
public SecurityConfiguration() {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/register", "/h2-console/**").permitAll()
.antMatchers("/**").authenticated()
.and().httpBasic();
http.headers().frameOptions().sameOrigin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我仍然收到以下错误,而不是所有这些设置:
Preflight response is not successful
Fetch API cannot load http://localhost:8000/api/register/ due to access control checks.
Failed to load resource: Preflight response is not successful
【问题讨论】:
标签: java spring spring-security cors fetch