【问题标题】:Spring Boot / React blocks CORSSpring Boot / React 阻止 CORS
【发布时间】:2021-06-20 01:16:57
【问题描述】:

我在本地主机上配置了一个使用 Spring Boot 的 api。 我的 Spring Boot 控制器应该允许 CORS 请求,因为我正在使用 @CrossOrigin:

@RestController
@CrossOrigin
@RequestMapping("/api")
public class imageController {
    @GetMapping("/images")
    public List<Image> findAll(){
        return imageService.findAll();
    }
}

使用 Postman / cURL 进行测试时,一切正常(但 cURL 并不关心 CORS 策略...)。 现在我正在尝试使用 axios 从我的 React 应用程序访问资源“http://localhost:8081/api/images”。 我得到以下响应标头,它确定请求因 CORS 而被阻止(请参阅“X-XSS-Protection”)。

Cache-Control
    no-cache, no-store, max-age=0, must-revalidate
Connection
    keep-alive
Date
    Tue, 23 Mar 2021 11:10:54 GMT
Expires
    0
Keep-Alive
    timeout=60
Pragma
    no-cache
Set-Cookie
    JSESSIONID=0683F0AD7647F9F148C9C2D4CED8AFE6; Path=/; HttpOnly
Transfer-Encoding
    chunked
Vary
    Origin
Vary
    Access-Control-Request-Method
Vary
    Access-Control-Request-Headers
WWW-Authenticate
    Bearer realm="Unknown"
X-Content-Type-Options
    nosniff
X-Frame-Options
    DENY
X-XSS-Protection
    1; mode=block

我的 axios 请求如下所示:

function findAll() {
    return instance.get('/api/images')
}

const instance = axios.create({
    baseURL: `${config.API_BASE_URL}`,
    headers: {
        'Content-Type': 'application/json'
    }
})

instance.interceptors.request.use(request => {
    console.log('Starting Request', JSON.stringify(request, null, 2))
    return request
})

instance.interceptors.response.use(response => {
    console.log('Response:', JSON.stringify(response, null, 2))
    return response
})

...通过以下代码调用:

    componentDidMount() {
        this.setState({ isLoading: true })
        ImageService.authToken(keycloak.token)
        ImageService.findAll().then((res) => {
            this.setState({ images: res.data, isLoading: false });
        });
    }

如何配置 Spring Boot 以允许此类请求,而不是通过 CORS 策略阻止我的请求?

请注意,我的应用程序受 keycloak 保护。但我认为 keycloak 的配置与这种情况无关。如果您需要 keycloak 的 Spring Boot 配置,请告诉我。

【问题讨论】:

    标签: reactjs spring-boot axios cors


    【解决方案1】:

    您好,您需要在您的 Spring Boot 项目中创建一个全局 cors 配置。创建一个类并使用 @Configuration 对其进行注释。您可以按照下面的示例进行操作。

    @Configuration
    public class MyConfiguration {
    
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
               registry.addMapping("/api/**")
                  .allowedOrigins("http://domain2.com")
                  .allowedMethods("PUT", "DELETE")
                  .allowedHeaders("header1", "header2", "header3")
                  .exposedHeaders("header1", "header2")
                  .allowCredentials(false).maxAge(3600);
            }
        };
      }
    }
    

    这里是spring框架提供的完整指南 https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

    【讨论】:

      【解决方案2】:

      您是否有可能会干扰的 Spring 安全配置 (@EnableWebSecurity / @EnableSpringSecurity)?如果是这样,您也可以在那里配置 cors()。

      @Configuration
      @EnableWebSecurity
      @EnableSpringSecurity
      class WebSecurityConfiguration(...)
      
      
        override fun configure(http: HttpSecurity) {
              http.cors().configurationSource {
                      CorsConfiguration().apply {
                          allowedOrigins = listOf("*")
                          allowedMethods = listOf("GET", "OPTIONS")
                          allowedHeaders = listOf("*")
                      }
                  }
      

      另见https://docs.spring.io/spring-security/site/docs/4.2.19.BUILD-SNAPSHOT/reference/html/cors.html

      【讨论】:

        猜你喜欢
        • 2021-07-03
        • 2021-01-23
        • 2021-08-17
        • 2020-05-03
        • 2021-02-10
        • 2020-09-10
        • 2020-07-05
        • 2021-07-03
        • 2021-10-30
        相关资源
        最近更新 更多