CORS与Spring Boot 2 [重复]

问题描述 投票:-1回答:3

我正在尝试将我的角度应用程序连接到我的新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"]}

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

java spring spring-boot cors
3个回答
1
投票

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


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("/**");
  }
}

最后在您的其余控制器类之上添加此注释:@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);
  }

}

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

© www.soinside.com 2019 - 2024. All rights reserved.