你能完全禁用Spring中的CORS支持吗?

bay*_*ezy 18 java spring spring-mvc swagger-codegen

正如描述的CORS预检要求失败,因为一个标准的头,如果你发送请求到OPTIONS与端点Origin和Access-Control-Request-Method设置,那么他们得到的Spring框架截获头,和你的方法没有得到执行.接受的解决方案是使用@CrossOrigin注释来阻止Spring返回a 403.但是,我使用Swagger Codegen生成我的API代码,所以我只想禁用它并OPTIONS手动实现我的响应.

那么你可以在Spring中禁用CORS拦截吗?

d0x*_*d0x 17

从他们的文件:

如果您使用的是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");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是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");
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

Yuriy Yunikov的回答也是正确的.但我不喜欢"自定义"过滤器.

万一你有Spring Web Security导致麻烦.检查这个 SO答案.

  • 此配置为所有源和所有端点启用CORS,发送"Access-Control-Allow-Origin:*",这与禁用它相反. (4认同)

Kir*_* Ch 14

我在 Spring Boot 应用程序中使用 Spring Security 并启用从特定域(或所有域)的访问。

我的网络安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // add http.cors()
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers("/get/**").permitAll()
                .antMatchers("/update/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .httpBasic(); // Authenticate users with HTTP basic authentication

        // REST is stateless
        http.sessionManagement()
               .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    // To enable CORS
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowedOrigins(ImmutableList.of("https://www.yourdomain.com")); // www - obligatory
//        configuration.setAllowedOrigins(ImmutableList.of("*"));  //set access from all domains
        configuration.setAllowedMethods(ImmutableList.of("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

}
Run Code Online (Sandbox Code Playgroud)

有时需要在测试前清除浏览器历史记录。

详细信息可以在这里看到:http : //appsdeveloperblog.com/crossorigin-restful-web-service/


仅适用于使用Angular 的人。我从 Angular 向后端运行请求:

export class HttpService {

  username = '..';
  password = '..';
  host = environment.api;
  uriUpdateTank = '/update/tank';

  headers: HttpHeaders = new HttpHeaders({
    'Content-Type': 'application/json',
    Authorization: 'Basic ' + btoa(this.username + ':' + this.password)
  });

  constructor(private http: HttpClient) {
  }

  onInsertTank(tank: Tank) {
    return this.http.put(this.host + this.uriUpdateTank, tank, {
      headers: this.headers
    })
      .pipe(
        catchError(this.handleError)
      );
  }
...
}
Run Code Online (Sandbox Code Playgroud)

旧版本。 在我的 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() {
    }

}
Run Code Online (Sandbox Code Playgroud)

  • http.cors().and().csrf().disable() 这就像魅力一样......干杯 (3认同)
  • 所有其他“现代”方法都失败了,但是这个“旧版本”方法成功了!太感谢了! (2认同)

200*_*0OK 12

如果您至少有 Java 8,请尝试这个:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 11

大多数答案都使用已弃用的 api。HttpSecurity以下代码片段将允许所有标头、方法和 url 使用spring配置的建议方法绕过 cors 安全规则

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.cors(httpSecurityCorsConfigurer -> 
        httpSecurityCorsConfigurer.configurationSource(request -> 
           new CorsConfiguration().applyPermitDefaultValues()
        )
    );
    return http.build();
}
Run Code Online (Sandbox Code Playgroud)


Yur*_*kov 9

尝试添加以下过滤器(您可以根据自己的需要和方法自定义它):

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这篇文章被低估了!无论出于何种原因,我都无法让 CORS 在 spring-boot-starter-web 中工作......这篇文章解决了它! (3认同)
  • 在尝试使用 Soring 2.6.7 **几个小时**之后(可能有问题,因为 @CrossOrigin 注释似乎不再在存储库上工作),这是 **唯一有效的解决方案** (2认同)

小智 8

以前的答案几乎都是关于启用 CORS,这对我来说是有效的禁用。

@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("*");
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)


Pan*_*hro 5

对于较新版本的spring boot:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*");
    }
}

Run Code Online (Sandbox Code Playgroud)

  • 没有工作 spring 2.6.7 java 18 (5认同)