如CORS preflight request fails due to a standard header中所述,如果您向OPTIONS
端点发送请求并设置了Origin
和Access-Control-Request-Method
标头,那么它们会被Spring框架拦截,并且您的方法会执行不被执行。接受的解决方案是使用@CrossOrigin
注释来阻止Spring返回403
。但是,我正在使用Swagger Codegen生成我的API代码,所以我只想禁用它并手动实现我的OPTIONS
响应。
那么你可以在Spring中禁用CORS拦截吗?
答案 0 :(得分:13)
如果您使用的是Spring Web MVC
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
如果您使用的是Spring Boot:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
};
}
}
Yuriy Yunikov的回答也是正确的。但我不喜欢" custom"过滤
如果你有Spring Web Security导致麻烦。检查this SO答案。
答案 1 :(得分:8)
尝试添加以下过滤器(您可以根据自己的需要和方法自定义它):
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addIntHeader("Access-Control-Max-Age", 10);
filterChain.doFilter(request, response);
}
}
答案 2 :(得分:1)
对于较新版本的spring boot:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
}
答案 3 :(得分:1)
以前的答案几乎都是关于启用 CORS 的,这对我来说禁用了。
function runRule(){
if(!workOrdersUploadCtrlr.files){
alert("No files have been selected!");
return;
}
var thefile = workOrdersUploadCtrlr.files;
var uploader = new XMLHttpRequest();
var file = new FormData();
for(var i=0; i < thefile.length; i++) {
if(workOrdersUploadCtrlr.cancelledFiles.indexOf(i) < 0){
file.append('file',thefile[i]);
uploader.onreadystatechange = function(){
if(uploader.readyState === 4 && uploader.status === 200){
console.log(uploader.responseText);
}
}
uploader.open('POST',"/url",true);
uploader.send(file);
}
}
}
答案 4 :(得分:0)
在我的Spring Boot应用程序中,没有其他方法可以工作了,
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type,x-auth-token, " +
"access-control-request-headers, access-control-request-method, accept, origin, authorization, x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
}
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
答案 5 :(得分:0)
如果您至少有Java 8,请尝试以下一种方法:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}
}