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

Spring Boot v2.5.2-CORS策略-"请求的资源上不存在访问控制允许起源标头"

曾歌者
2023-03-14

我有一个带有Vue JS的前端应用程序,我使用axios调用我的Spring BootAPI,使用Spring Security性。

Vue运行在http://localhost:8081上。API在http://localhost:8080上运行

我的Spring Boot应用程序设置如下:

application.properties:空

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demin</groupId>
    <artifactId>api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

应用程序:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}

IndexController:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://localhost:8081/")
@RestController
@RequestMapping("/api")
public class IndexController {
        
    @GetMapping("/index") 
    public ResponseEntity<String> findTitle()  {
        System.err.println("Hello IndexController !");
        return new ResponseEntity<>("Hello world", HttpStatus.OK);
    }
}

SecurityConfig:

import java.util.List;
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;
import org.springframework.web.cors.CorsConfiguration;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
        corsConfiguration.setAllowedOrigins(List.of("http://localhost:8081"));
        corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT","OPTIONS","PATCH", "DELETE"));
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setExposedHeaders(List.of("Authorization"));      

        http
            .authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .csrf().disable()
            .cors().configurationSource(request -> corsConfiguration);
    }
}

现在,当我从Vue js打电话时:

axios.get('http://localhost:8080/api/index')
  .then((response) => {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

我的浏览器返回:

CORS策略阻止了从http://localhost:8080/api/indexhttp://localhost:8081对XMLHttpRequest的访问:请求的资源上不存在访问控制允许起源标头。

这似乎是一个经常出现的问题,所以我尝试了很多“解决方案”,但我显然错过了一些东西,我需要一些帮助。。。

编辑#2:

import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.formLogin().disable();
            
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

返回相同的错误。

编辑#3:

2021-07-23 07:39:49.050  INFO 3924 --- [  restartedMain] com.demin.api.ApiApplication             : No active profile set, falling back to default profiles: default
2021-07-23 07:39:49.082  INFO 3924 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-07-23 07:39:49.082  INFO 3924 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-07-23 07:39:49.533  INFO 3924 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-07-23 07:39:49.542  INFO 3924 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JPA repository interfaces.
2021-07-23 07:39:49.983  INFO 3924 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-07-23 07:39:49.992  INFO 3924 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-23 07:39:49.992  INFO 3924 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-23 07:39:50.063  INFO 3924 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-07-23 07:39:50.064  INFO 3924 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 980 ms
2021-07-23 07:39:50.084  INFO 3924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-07-23 07:39:50.220  INFO 3924 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-07-23 07:39:50.225  INFO 3924 --- [  restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:966f4eb4-9170-4c8f-a106-67ce4bac32bd'
2021-07-23 07:39:50.354  INFO 3924 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-07-23 07:39:50.395  INFO 3924 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-07-23 07:39:50.496  INFO 3924 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-07-23 07:39:50.592  INFO 3924 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-07-23 07:39:50.763  INFO 3924 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-07-23 07:39:50.771  INFO 3924 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-07-23 07:39:50.803  WARN 3924 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-07-23 07:39:51.019  INFO 3924 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 5d615eab-a8ac-4024-9fc0-be44e58ac78e

2021-07-23 07:39:51.109  INFO 3924 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d114f4, org.springframework.security.web.context.SecurityContextPersistenceFilter@3c920c43, org.springframework.security.web.header.HeaderWriterFilter@45adf32d, org.springframework.security.web.csrf.CsrfFilter@59560611, org.springframework.security.web.authentication.logout.LogoutFilter@3101ec7e, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@65bc50ad, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@2439fa5a, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@4f62b51e, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@42ca4d2d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@3765695a, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@154842ed, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5f512afa, org.springframework.security.web.session.SessionManagementFilter@180f71e7, org.springframework.security.web.access.ExceptionTranslationFilter@46815abf, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@611036c4]
2021-07-23 07:39:51.145  INFO 3924 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2021-07-23 07:39:51.173  INFO 3924 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-07-23 07:39:51.182  INFO 3924 --- [  restartedMain] com.demin.api.ApiApplication             : Started ApiApplication in 2.434 seconds (JVM running for 3.184)

共有1个答案

羊舌洛华
2023-03-14

这个问题与CORS无关。

在回顾了提供的小示例之后,问题在于文件夹结构。

Springs的主要功能由api文档中的注释@SpringBootApplication注释:

这是一个方便的注释,相当于声明@Configuration、@EnableAutoConfiguration和@ComponentScan。

对于@ComponentScan的留档,它表示以下内容:

将组件扫描指令配置为与@Configuration类一起使用。。。如果未定义特定的包,将从声明此注释的类的包中进行扫描。

注意最后一部分。

因此,Spring将扫描用@SpringBootApplication注释的类下面的所有包,以搜索用@Configuration注释的类。

提供的项目目录布局如下所示:

java
├── com
│   └─ demin
│        └── api
│             └── @SpringBootApplication
├── config
│      └── @Configuration
└── controller
       └── @RestController

这意味着没有任何带注释的类将从扫描中拾取。

所以解决问题的方法是目录结构需要更改为:

java
└── com
    └─ demin
         └── api
              ├── @SpringBootApplication
              ├── config
              │     └── @Configuration
              └── controller
                    └── @RestController

让spring能够扫描底层包并获取带注释的类。

或者,如果希望spring扫描特定位置中的特定包,则可以在@ComponentScan注释中定义basePackageClasses()basePackages()。或者只是特定的类。

当您拉入spring security starter时,您会得到一个为您定义的自动配置,该配置在《spring security参考手册》的Hello spring security部分中定义

由于应用程序扫描甚至没有拾取任何定义的配置,所以这是当前正在使用的配置。其余终结点也未加载。

如果启用并提供了配置和endpoint,则可能会在调试日志中发现未加载的配置和endpoint。

那么,如何防止这种情况发生:

>

  • 始终使用Spring初始值设定项来生成项目。

    遵循来自可靠来源的教程,例如spring提供了几个入门指南

    了解如何在spring应用程序的不同部分或例如spring security中启用调试日志记录

    在配置中设置断点,并检查它是否在启动时运行。

  •  类似资料:
    • 我试着把数据从React.jslocalhostinsert.php文件。当我提交的形式从reactjs它给我错误的控制台错误是: 访问位于“”的XMLHttpRequesthttp://localhost/reactphpdemo/connect.php“起源”http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access

    • 我已经创建了两个web应用程序--客户端和服务应用程序。 当客户端和服务应用程序部署在同一个Tomcat实例中时,它们之间的交互很好。 但是当应用程序部署到分开的Tomcat实例(不同的机器)时,当请求发送服务应用程序时,我会得到以下错误。 我的客户端应用程序使用JQuery、HTML5和bootstrap。

    • 它是一个服务类,如下所示: 我试图通过将用户名和密码添加为let来发送用户名和密码,但它说我被CORS策略阻止了。 在这里,我在我的春靴里补充道: 在controller类中: 来自网络选项卡的消息

    • 我犯了这个错误 无法加载XMLHttpRequesthttp://domain.com/canvas/include/rs-plugin/js/extensions/revolution.extension.video.min.js.飞行前响应中的访问控制允许标头不允许请求标头字段X-Requested-With。 我的php页面顶部有这两行代码,用于加载这个js文件。 但是问题依然存在,我该怎么

    • 我使用从使用API的ReactJS发送数据,我得到一个错误: 以下是错误: CORS策略已阻止从来源“http://localhost/2019/EURDU/user_controllers/userregistercontroller/userregistration”访问位于“http://localhost:3000”的XMLHttpRequest:飞行前响应中的access-control

    • 当我试图从另一个域访问rest服务时,我得到了以下错误 无法加载对飞行前请求的响应没有通过访问控制检查:请求的资源上没有“访问-控制-允许-起源”标头。因此,不允许访问源'http://localhost:8080'。 我将服务器端配置为响应跨域调用,这可以用于GET调用,但POST调用会产生错误 谢谢