CORS与Spring Boot 2 [重复]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CORS与Spring Boot 2 [重复]相关的知识,希望对你有一定的参考价值。

我正在尝试将我的角度应用程序连接到我的新Spring Boot 2控制器。我开始一切,我得到:

Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

其次是:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}

所以这是CORS,对吧?当我从邮递员那里击中localhost:8093/restapi/setup时,我得到了一个有效的回应,正如你所期望的那样。

所以我做了一些研究,特别是我发现:No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

我终于在这里找到了这篇文章:

https://chariotsolutions.com/blog/post/angular-2-spring-boot-jwt-cors_part1/

这导致我得到以下代码:

@Configuration
public class ManageConfiguration {
    private static final Logger         LOGGER = LogManager.getLogger(ManageConfiguration.class);

    @Bean
    public CorsFilter corsFilter() {
        LOGGER.debug("Configuring CORS");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

所以我认为这很简单,现在再试一次,我得到:

Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

其次是:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}

所以它似乎没有任何区别。

检查并在正确的端口上运行:

2019-02-27 14:23:21.261  INFO 9814 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8093 (http) with context path ''

确保它包含我的CORS bean:

2019-02-27 14:23:19.608 DEBUG 9814 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'corsFilter'
...
o.springframework.web.filter.CorsFilter  : Filter 'corsFilter' configured for use

根据How can you debug a CORS request with cURL?,我做了以下卷曲请求,看看我的飞行前的东西。

$ curl -H "Origin: http://example.com" --verbose http://localhost:8093/restapi/setup
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8093 (#0)
> GET /restapi/setup HTTP/1.1
> Host: localhost:8093
> User-Agent: curl/7.61.0
> Accept: */*
> Origin: http://example.com
> 
< HTTP/1.1 200 
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< Access-Control-Allow-Origin: http://example.com
< Access-Control-Allow-Credentials: true
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Wed, 27 Feb 2019 21:38:28 GMT
< 
* Connection #0 to host localhost left intact
{"issueType":["bug","epic","subTask","task","story"]}

我一直在摸不着头脑,想知道下一步该怎么办,也无法想出任何东西。建议?

答案

我想你在请求URL中发送了一个没有http://协议前缀的ajax请求,尝试从ajax中点击http://localhost:8093/restapi/setup

另一答案

在您的代码中添加此WebSecurityConfigurerAdapter

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

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

}

还添加以下WebMvcConfigurer

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfigurerImpl implements WebMvcConfigurer {

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

最后在您的其余控制器类之上添加此注释:@CrossOrigin。

@CrossOrigin
public class RestController {
// Your methods
}

如果您有过滤器,则可以将以下属性添加到响应中,如果没有,则可以使用此属性。

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

@Service
public class JwtAuthenticationFilter extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
    response.setHeader("Access-Control-Expose-Headers", "Content-Length, Authorization");
    filterChain.doFilter(request, response);
  }

}
另一答案
@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
                        .allowedHeaders("*");
            }
        };
    }
}

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

请在这里查看教程https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

以上是关于CORS与Spring Boot 2 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

带有 Google 的 OAuth2 - CORS 错误(Angular + Spring boot)[重复]

无法使用 Spring Boot 和 Angular 修复 CORS 问题 [重复]

Zuul Proxy CORS 头包含多个值,头重复两次 - Java Spring Boot CORS 过滤器配置

Spring Boot CORS支持

Angular 2 + CORS + 带有 Spring Security 的 Spring Boot Rest Controller

Spring Boot 中的 CORS 与 Spring Security + React