带有Spring Boot 2的CORS

时间:2019-02-27 20:20:27

标签: java spring spring-boot cors

我正在尝试将我的角度应用程序连接到新的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请求,以查看飞行前物品。

$ 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"]}

对于接下来要尝试的内容,我scratch了一天的脑袋,无计可施。有建议吗?

3 个答案:

答案 0 :(得分:1)

我认为您要在请求URL中发送不带http://协议前缀的ajax请求,请尝试从ajax中访问http://localhost:8093/restapi/setup

答案 1 :(得分:0)

在您的代码中添加此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("/**");
  }
}

最后,将此注释添加到您的rest控制器类的顶部:@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);
  }

}

答案 2 :(得分:0)

@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