spring CORS问题-请求的资源上不存在“Access-Control-Allow-Origin”标头

svmlkihl  于 2022-10-30  发布在  Spring
关注(0)|答案(8)|浏览(364)

我已经创建了两个Web应用程序-客户端和服务应用程序。
当客户端和服务应用程序部署在同一Tomcat示例中时,它们之间的交互会很好。
但当应用程序部署到单独的Tomcat示例(不同的机器),我得到下面的错误时,请求发送服务应用程序。

  1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  2. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401

我的客户端应用程序使用JQuery、HTML5和Bootstrap。
对服务进行 AJAX 调用,如下所示:

  1. var auth = "Basic " + btoa({usname} + ":" + {password});
  2. var service_url = {serviceAppDomainName}/services;
  3. if($("#registrationForm").valid()){
  4. var formData = JSON.stringify(getFormData(registrationForm));
  5. $.ajax({
  6. url: service_url+action,
  7. dataType: 'json',
  8. async: false,
  9. type: 'POST',
  10. headers:{
  11. "Authorization":auth
  12. },
  13. contentType: 'application/json',
  14. data: formData,
  15. success: function(data){
  16. //success code
  17. },
  18. error: function( jqXhr, textStatus, errorThrown ){
  19. alert( errorThrown );
  20. });
  21. }

我的服务应用程序使用Spring MVC、Spring Data JPA和Spring Security。
我已经包含了CorsConfiguration类,如下所示:
CORSConfig.java

  1. @Configuration
  2. @EnableWebMvc
  3. public class CORSConfig extends WebMvcConfigurerAdapter {
  4. @Override
  5. public void addCorsMappings(CorsRegistry registry) {
  6. registry.addMapping("*");
  7. }
  8. }

SecurityConfig.java

  1. @Configuration
  2. @EnableGlobalMethodSecurity(prePostEnabled = true)
  3. @EnableWebSecurity
  4. @ComponentScan(basePackages = "com.services", scopedProxy = ScopedProxyMode.INTERFACES)
  5. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  6. @Autowired
  7. @Qualifier("authenticationService")
  8. private UserDetailsService userDetailsService;
  9. @Bean
  10. @Override
  11. public AuthenticationManager authenticationManagerBean() throws Exception {
  12. return super.authenticationManagerBean();
  13. }
  14. @Override
  15. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  16. auth.userDetailsService(userDetailsService);
  17. auth.authenticationProvider(authenticationProvider());
  18. }
  19. @Override
  20. protected void configure(HttpSecurity http) throws Exception {
  21. http
  22. .authorizeRequests()
  23. .antMatchers("/login").permitAll()
  24. .anyRequest().fullyAuthenticated();
  25. http.httpBasic();
  26. http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  27. http.csrf().disable();
  28. }
  29. @Bean
  30. public PasswordEncoder passwordEncoder() {
  31. return new BCryptPasswordEncoder();
  32. }
  33. @Bean
  34. public DaoAuthenticationProvider authenticationProvider() {
  35. DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
  36. authenticationProvider.setUserDetailsService(userDetailsService);
  37. authenticationProvider.setPasswordEncoder(passwordEncoder());
  38. return authenticationProvider;
  39. }
  40. }

Spring安全依赖项:

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-config</artifactId>
  4. <version>3.2.3.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.security</groupId>
  8. <artifactId>spring-security-web</artifactId>
  9. <version>3.2.3.RELEASE</version>
  10. </dependency>

我正在使用Apache Tomcat服务器进行部署。

mtb9vblg

mtb9vblg1#

CORS的预检请求使用没有凭据的HTTP OPTIONS,请参阅跨源资源共享:
否则,请发出预检请求。使用OPTIONS方法,并使用以下附加约束条件,使用引用源作为覆盖引用源,从原始源origin获取请求URL,并设置手动重定向标志和阻止Cookie标志:

  • 包括Access-Control-Request-Method标头,并将请求方法(即使是简单方法)作为标头字段值。
  • 如果作者请求标头不为空,则应包含Access-Control-Request-Headers标头,并将其标头字段值作为作者请求标头中以逗号分隔的标头字段名称列表(按字典顺序排列),每个标头字段名称都将转换为ASCII小写字母(即使其中一个或多个标头是简单标头)。
  • 排除作者请求标头。
  • 排除使用者认证。
  • 排除请求实体正文。

您必须允许匿名访问HTTP OPTIONS

Spring 安全3

您的修改(和简化)代码:

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http
  4. .authorizeRequests()
  5. .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
  6. .antMatchers("/login").permitAll()
  7. .anyRequest().fullyAuthenticated()
  8. .and()
  9. .httpBasic()
  10. .and()
  11. .sessionManagement()
  12. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  13. .and()
  14. .csrf().disable();
  15. }

您仍需要CORS配置(可能带有一些附加值):

  1. @Configuration
  2. @EnableWebMvc
  3. public class CORSConfig extends WebMvcConfigurerAdapter {
  4. @Override
  5. public void addCorsMappings(CorsRegistry registry) {
  6. registry.addMapping("*");
  7. }
  8. }

Spring 安全4

从Spring Security 4.2.0开始你就可以使用内置的支持,参见Spring Security Reference

19. CORS系统

Spring框架为CORS提供了一流的支持。CORS必须在Spring Security之前处理,因为预检请求将不包含任何cookie(即JSESSIONID)。如果请求不包含任何cookie,并且Spring Security是第一个,则该请求将确定用户未通过身份验证(因为请求中没有cookie)并拒绝它。
确保首先处理CORS的最简单方法是使用CorsFilter。用户可以通过使用以下代码提供CorsConfigurationSource来将CorsFilter与Spring Security集成:

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http
  6. // by default uses a Bean by the name of corsConfigurationSource
  7. .cors().and()
  8. ...
  9. }
  10. @Bean
  11. CorsConfigurationSource corsConfigurationSource() {
  12. CorsConfiguration configuration = new CorsConfiguration();
  13. configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
  14. configuration.setAllowedMethods(Arrays.asList("GET","POST"));
  15. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  16. source.registerCorsConfiguration("/**", configuration);
  17. return source;
  18. }
  19. }
展开查看全部
wfsdck30

wfsdck302#

从Spring Security 4.1开始,这是使Spring Security支持CORS的正确方法(在Sping Boot 1.4/1.5中也需要):

  1. @Configuration
  2. public class WebConfig extends WebMvcConfigurerAdapter {
  3. @Override
  4. public void addCorsMappings(CorsRegistry registry) {
  5. registry.addMapping("/**")
  6. .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
  7. }
  8. }

以及:

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. // http.csrf().disable();
  6. http.cors();
  7. }
  8. @Bean
  9. public CorsConfigurationSource corsConfigurationSource() {
  10. final CorsConfiguration configuration = new CorsConfiguration();
  11. configuration.setAllowedOrigins(ImmutableList.of("*"));
  12. configuration.setAllowedMethods(ImmutableList.of("HEAD",
  13. "GET", "POST", "PUT", "DELETE", "PATCH"));
  14. // setAllowCredentials(true) is important, otherwise:
  15. // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
  16. configuration.setAllowCredentials(true);
  17. // setAllowedHeaders is important! Without it, OPTIONS preflight request
  18. // will fail with 403 Invalid CORS request
  19. configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
  20. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  21. source.registerCorsConfiguration("/**", configuration);
  22. return source;
  23. }
  24. }
  • 不要 * 执行以下任何错误的尝试解决问题的方法:
  • web.ignoring().antMatchers(HttpMethod.OPTIONS);
  • web.ignoring().antMatchers(HttpMethod.OPTIONS);

参考:http://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html

展开查看全部
plupiseo

plupiseo3#

在我的例子中,我有一个启用了OAuth安全的资源服务器,上面的任何一个解决方案都不起作用。

  1. @Bean
  2. public FilterRegistrationBean corsFilter() {
  3. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  4. CorsConfiguration config = new CorsConfiguration();
  5. config.setAllowCredentials(true);
  6. config.addAllowedOrigin("*");
  7. config.addAllowedHeader("*");
  8. config.addAllowedMethod("*");
  9. source.registerCorsConfiguration("/**", config);
  10. FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
  11. bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
  12. return bean;
  13. }

基本上在这个例子中Ordered.HIGHEST_PRECEDENCE是关键!
https://github.com/spring-projects/spring-security-oauth/issues/938
不同的pom依赖项添加了不同种类的过滤器,因此我们可能会有基于顺序的问题。

展开查看全部
atmip9wb

atmip9wb4#

由于这些例子对我都没有帮助,所以我就用我自己的知识来处理问题。通常最复杂的bug总是发生在我身上。所以这就是我处理这个bug的方法。
在此方法中:

  1. @Bean
  2. CorsConfigurationSource corsConfigurationSource() {
  3. CorsConfiguration cors = new CorsConfiguration();
  4. cors.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "HEAD", "DELETE"));
  5. UrlBasedCorsConfigurationSource source = new
  6. UrlBasedCorsConfigurationSource();
  7. source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
  8. return source;
  9. }

CorsConfiguration默认有允许的方法:POST,HEAD,GET,所以PUT,DELETE都不起作用!我所做的就是创建CorsConfiguration的新示例并设置允许的方法:

  1. cors.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "HEAD", "DELETE"));

所以现在我的方法看起来像:

  1. @Bean
  2. CorsConfigurationSource corsConfigurationSource() {
  3. CorsConfiguration cors = new CorsConfiguration();
  4. cors.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "HEAD", "DELETE"));
  5. UrlBasedCorsConfigurationSource source = new
  6. UrlBasedCorsConfigurationSource();
  7. source.registerCorsConfiguration("/**", cors.applyPermitDefaultValues());
  8. return source;
  9. }

而且它的工作方式很有魅力。我希望它能帮助到一些人。当然,所有其他的配置都是由spring.io文档进行的

展开查看全部
0kjbasz6

0kjbasz65#

在主应用程序中添加以下配置。它在Spring Boot应用程序2.3.1中工作

  1. package com.example.restservicecors;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7. @SpringBootApplication
  8. public class RestServiceCorsApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(RestServiceCorsApplication.class, args);
  11. }
  12. @Bean
  13. public WebMvcConfigurer corsConfigurer() {
  14. return new WebMvcConfigurer() {
  15. @Override
  16. public void addCorsMappings(CorsRegistry registry) {
  17. registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*");
  18. }
  19. };
  20. }
  21. }

参考源https://spring.io/guides/gs/rest-service-cors/

展开查看全部
46qrfjad

46qrfjad6#

试试看:

  1. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.core.Ordered;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.web.cors.CorsConfiguration;
  6. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  7. import org.springframework.web.filter.CorsFilter;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. @Component
  11. public class CorsFilterConfig {
  12. public static final List<String> allowedOrigins = Arrays.asList("*");
  13. @Bean
  14. public FilterRegistrationBean<CorsFilter> initCorsFilter() {
  15. // @formatter:off
  16. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  17. CorsConfiguration config = new CorsConfiguration();
  18. config.setAllowCredentials(true);
  19. config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
  20. config.addAllowedMethod("*");
  21. config.setAllowedOrigins(allowedOrigins);
  22. source.registerCorsConfiguration("/**", config);
  23. FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
  24. bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
  25. return bean;
  26. // @formatter:on
  27. }
  28. }
展开查看全部
q8l4jmvw

q8l4jmvw7#

如果你使用UsernamePasswordAuthenticationFilter,你可以很容易地添加@CrossOrigin注解来允许所有这些,并且在安全配置中添加http.cors().和().这对我来说很有效。

  1. @CrossOrigin(origins = "*")
  2. public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  3. private final AuthenticationManager authenticationManager;
  4. @Override
  5. protected void configure(HttpSecurity http) throws Exception {
  6. CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean());
  7. customAuthenticationFilter.setFilterProcessesUrl("/api/login");
  8. http.csrf().disable();
  9. http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  10. // We can ant match out paths to the corresponding roles --> we allow certain roles to access certain API's
  11. http.cors().and();
  12. http.authorizeRequests().antMatchers(HttpMethod.POST, "/**").permitAll();

...

展开查看全部
lstz6jyr

lstz6jyr8#

这适用于:Spring启动器2.2.6.释放

  1. @Configuration
  2. @EnableWebMvc
  3. public class WebConfig implements WebMvcConfigurer {
  4. @Override
  5. public void addCorsMappings(CorsRegistry registry) {
  6. registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*");
  7. }
  8. }

将“*”变更为生产中有意义的项目

相关问题