当前位置: 首页 > 知识库问答 >
问题:

Spring启动/反应阻止CORS

杜英范
2023-03-14

我在本地主机上用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从我的反应应用程序中访问重新来源“http://localhost:8081/api/images”。我得到以下响应头,它确定请求因CORS而被阻止(请参见“X-XSS-保护”)。

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策略阻止我的请求?

请注意,我的应用程序由KeyClope保护。但我不认为KeyClope的配置与本案有关。请让我知道,如果你需要的钥匙斗篷Spring开机配置。

共有2个答案

居飞扬
2023-03-14

您是否有可能会干扰的Spring Security配置(@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

廉鸿运
2023-03-14

您好,您需要在您的Spring启动项目中创建一个全局cors配置。创建一个类并用@配置注释它。您可以遵循下面的示例。

@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

 类似资料:
  • 我们正在设置一个由Keycloak身份验证服务器备份的spring boot(V2.0.5)服务器应用程序。 Keycloak提供了一些Java管理API(keycloak-admin-client),不幸的是,这些API需要org.jboss.resteasy.resteasy-client包中的ResteasyClient作为依赖项。 但是,如果我将此依赖项添加到POM中作为 服务器启动时出现

  • 同时使用redux与反应。我试图在安装react-redux和redux库后,为我的应用程序(reactwiseldux)进行npm启动。我在下面看到这个错误。我自己也在想办法,但目前还没找到。请帮帮我。 “反应脚本”不被识别为内部或外部命令、可操作程序或批处理文件。npm错误!代码ELIFECYCLE npm ERR!错误1 npm错误!reactwithredux@0.1.0开始:npm ER

  • 我试图运行我的spring boot应用程序,设置了以下属性,我希望它继续重试从配置服务器加载属性50次,在任何两次尝试之间等待6秒,即使在此之后,它不能连接到配置服务器,它应该恢复启动或退出(我对重试后spring boot能够做的事情无所谓)。但它似乎并不像预期的那样表现。 我的启动命令- 如果您想要一个嵌入式数据库,请在类路径上放置一个受支持的数据库。如果要从特定配置文件加载数据库设置,则可

  • 问题内容: 我正在玩最近添加的angular.js动画功能,但这并不能正常工作 http://jsfiddle.net/Kx4TS/1 它会破坏myDiv上的内容,并使其逐渐消失。最初应将其隐藏。如何解决? 问题答案: 现在,此问题已得到解决。升级到1.1.5。

  • 我陷入了这个问题:我在后端使用Spring启动应用程序,在前端使用角度应用程序,问题是当我在后端调用一个特定的Rest网址时,该URL使用我已添加到后端的jar依赖项作为maven系统范围依赖项,我得到一个cors错误。所有其他后端网址工作正常 这是我如何包含后端的jar依赖项: 还要注意,我在前端和后端之间使用了Zuul调度程序,并且我在后端进行了此配置 公共类 CorsFilter 扩展 On

  • 我是EHCache的新手,尝试将其用作我们的缓存服务器。我写了代码试图开始: 在类路径中,我已经包含了terra cotta-toolkit-1.6-5 . 2 . 0 . jar、terra cotta-toolkit-1.6-runtime-5.0 . 0、slf4j-api-1.6.6、slf4j-jdk14-1.6.6、ehcache-2.7.0和ehcache-ee-2.7.0 我有eh