【发布时间】:2019-07-16 23:09:48
【问题描述】:
我正在使用 Spring Boot 版本 2.0.8.RELEASE 和 spring-boot-start-security 模块。 我正在尝试使用基本身份验证来保护我的招摇端点,到目前为止一切顺利。 但是,我的代码中来自 javascript 的请求已经开始失败,并出现以下错误
Access to XMLHttpRequest at 'http://my-service.com.com/search/api/getQuery' from origin 'http://myui.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
我定义了以下配置类
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//See https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-global-java for configuring cors
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
}
}
我的 API 类上有 @CrossOrigin 注释。
我有以下课程来配置我的安全性
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/v2").authenticated()
.antMatchers("/swagger-resources").authenticated()
.antMatchers("/swagger-ui.html").authenticated()
.and()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.and();
}
}
我尝试在安全类中创建一个 CorsConfiguration 并删除 @CrossOrigin 注释,但这也不起作用。 知道我需要做什么才能让 cors 在 Spring Boot 2.0.8.RELEASE 上正常工作吗?
谢谢 达米安
【问题讨论】:
-
您的前端 JavaScript 代码正在触发您的浏览器发送 CORS preflight OPTIONS 请求,并且服务器以 3xx 重定向响应。它需要以 2xx 成功消息来响应。
-
@sideshowbarker 我不认为这个问题是重复的。我正在按照 Spring 站点关注文档,但出现此错误。我不想一起破解解决方案,因为这最终会导致更多麻烦
-
问题中引用的错误消息表明您发送请求的服务器正在使用 3xx 重定向而不是 2OO OK 响应 OPTIONS 请求。这正是问题中描述的问题,这被标记为重复。为了让这里的其他人能够为您提供帮助,您需要更新问题,例如,有关服务器尝试将请求重定向到哪个 URL 的详细信息。基本上,这个重复的另一个问题中已经描述的内容。目前所写的问题并未表明该重定向是问题的意识。
-
@sideshowbarker 这个问题专门针对 Spring Boot 设置和配置。您的答案是针对 ASP.net。这是一个相关的问题,可以自行解决
标签: java spring-boot spring-security cors