CORS
由于安全原因,浏览器不允许 JavaScript 访问当前源(origin)之外的内容。跨域资源共享(Cross-Origin Resource Sharing 或 CORS)解决了这个问题,因为可以指定允许哪些跨域请求。
默认情况下,REST API 允许所有的跨域请求。如需限制源列表,可以定义 jmix.cors.allowed-origins 应用程序属性,以及其他 CORS 配置。
CORS 配置会自动应用在下列 URL:
-
/rest/**
-
/oauth/**
-
定义在 jmix.rest.authenticated-url-patterns 中的 URL patterns。
如果需要在其他 URL 路径使用 CORS 配置,请定义下面的 bean(可以在应用程序主类中定义):
@Bean
public WebSecurityConfigurerAdapter mySecurityConfigurerAdapter() {
return new WebSecurityConfigurerAdapter() {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers(requestMatchers ->
requestMatchers.antMatchers("/myapi/hello")
)
.cors(Customizer.withDefaults())
.authorizeRequests(authorize ->
authorize.anyRequest().permitAll()
);
}
};
}
如果需要替换 Jmix 提供的默认 CORS 配置,请在项目中使用 corsConfigurationSource
名称注册一个 bean。此时,上面提到的那些应用程序属性将失效。
参考 Spring Security 文档 了解更多关于 CORS 的信息。
本页是否有帮助?
感谢您的反馈