spring-boot - Spring Data REST 缺少 CORS 标头“Access-Control-Allow-Origin”
问题描述
我正在尝试解决 CORS 问题,spring data rest
但似乎没有附加 CORS 标头。这是我的配置:
@Component
class DataRestConfig: RepositoryRestConfigurer {
override fun configureRepositoryRestConfiguration(config: RepositoryRestConfiguration?, cors: CorsRegistry?) {
cors?.addMapping("/*")
?.allowedOrigins("*")
?.allowedMethods("GET", "PUT", "DELETE","PATCH","POST","OPTIONS")
}
}
我对其他没有弹簧数据休息的 API 路由也有同样的问题。这是我的WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
open class WebSecurityConfig(private val userDetailsServices: DatabaseUserDetailsServices, private val jwtService: JWTService): WebSecurityConfigurerAdapter() {
@Value("\${auth.jwt.secret}")
private var secret: String = ""
override fun configure(http: HttpSecurity) {
http
.cors().and()
.csrf().disable()
.addFilterAfter(JWTAuthorizationFilter(userDetailsServices, secret, jwtService),UsernamePasswordAuthenticationFilter::class.java)
.authorizeRequests()
.antMatchers(HttpMethod.POST,UserController.LOGIN_URL).permitAll()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated()
}
}
编辑:
- 添加了完整的
WebSecurityConfigurerAdapter
- 我注意到 OPTIONS 请求得到 403 这就是为什么我添加了
antMatchers
for OPTIONS 方法但它没有帮助。 - 这是响应和请求标头。没有响应正文:
解决方案
如果使用 Spring MVC,您应该像这样配置 CORS 行为
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS");
}
}
推荐阅读
- javascript - 铯如何使用路径位置绘制折线
- html - 从选择选项中选择 HTML 突然消失
- android - Gradle 错误程序类型已存在:org.java_websocket.AbstractWebSocket$1
- flutter - Flutter :- 这个 AdWidget 已经在 Widget 树中。如何禁用此异常。这是什么意思?
- ruby-on-rails - 如何更改 Rails 中无效日期的内置默认 date_select 通知消息?
- azure - 支持在 azure 搜索中上传同义词词典
- c++ - cin 无论如何会影响 c++ 中新关键字的使用吗?
- node.js - Prerender 获取数据的 React 页面
- spring - 如果 @Configuration 类中存在空构造函数,则 Spring @DynamicPropertySource 不起作用
- php - .htaccess 删除 "?page="