java - Spring Boot、Cors 和 Spring Security
问题描述
我正在使用 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 上正常工作吗?
谢谢达米安
解决方案
以我的经验,Spring Annotations 从未成功解决 CORS 问题。我首选的解决方案是通过虚拟主机路由两个服务器(在我的情况下为 Node 和 Tomcat)。
在我的 Apache httpd-vhosts 配置文件中,我有以下设置。
ProxyRequests Off
ProxyPreserveHost Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location /FrontEndServer>
ProxyPass http://localhost:8080/FrontEndServer connectiontimeout=333 timeout=999
ProxyPassReverse http://localhost:8080/FrontEndServer
</Location>
<Location />
ProxyPass http://localhost:3000/ connectiontimeout=333 timeout=999
ProxyPassReverse http://localhost:3000/
</Location>
在这个设置中,我的两台服务器在不同的端口上运行,但 Apache 正在重新路由它们,以便它们可以共享我的本地主机,并通过“/”或“/FrontEndServer”来区分。
显然,这是特定于 Apache 的,可能不是您使用的设置。但是,您应该能够使用这些原则为您的具体情况找到解决方案。希望这可以帮助。
推荐阅读
- php - 如何在 PHP 中单击按钮时向数组添加更多值
- boost - 无法从 VS2019 中的 Boost 属性树映射值中获取值()
- node.js - 错误:EISDIR:对 nodeJS 中目录的非法操作
- kivy - 我正在尝试让这个屏幕切换到 kivy
- solr - Solr 自定义随机字段基于字段值
- odata - SEGW 警告 Edm.DateTime 的“潜在数据丢失”
- flutter - UI 未更新无状态小部件
- pandas - 如何重组表(熊猫)?
- python - 引用外部资源时正确使用 __del__
- python - 使用 Python 图像库而不是 Matplotlib 映射投影,然后将图像扭曲到另一个投影?