首页 > 解决方案 > 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()
    }
}

编辑:

  1. 添加了完整的WebSecurityConfigurerAdapter
  2. 我注意到 OPTIONS 请求得到 403 这就是为什么我添加了antMatchersfor OPTIONS 方法但它没有帮助。
  3. 这是响应和请求标头。没有响应正文:

在此处输入图像描述

标签: spring-bootkotlincorsspring-data-rest

解决方案


如果使用 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");
    }
}

推荐阅读