Spring 即使设置了交叉原点,仍然面对CORS

Spring 即使设置了交叉原点,仍然面对CORS,spring,spring-boot,cors,Spring,Spring Boot,Cors,我想从Angular应用程序调用Spring API: login(user: User) : Observable<User> { return this.http.post(this._baseUrl + 'users/login', user) .map((response: Response) => { let utilisateur = response.json(); if (utilisate

我想从Angular应用程序调用Spring API:

login(user: User) : Observable<User> {
    return this.http.post(this._baseUrl + 'users/login', user)
        .map((response: Response) => {
            let utilisateur = response.json();
            if (utilisateur) {
                sessionStorage.setItem('currentUser', JSON.stringify(utilisateur));
                this.setAuthState(AuthState.LOGGED_IN);
            }
            return utilisateur;
        });
  }
在@Configuration类中:

@Configuration
@PropertySource("classpath:application.properties")
public class Config implements EnvironmentAware {

    @SuppressWarnings("unused")
    @Autowired
    private Environment env;
    
    @Override
    public void setEnvironment(final Environment environment) {
        this.env = environment;
    }
    
    public ObjectMapper objectMapper(){
         ObjectMapper mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
            mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
            mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
            mapper.setVisibility(mapper.getSerializationConfig()
                    .getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                    .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                    .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                    .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
            mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
            return mapper;
    }
    
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
    
    @Value("${path.file}")
    public String pathFile;
    
    ...
    
}
以下是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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edm</groupId>
    <artifactId>gmao</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>gmao</name>
    <description>project for GMAO</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        ...
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        ...
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>2.0</version>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
                    
        </plugins>
    </build>

</project>

4.0.0
com.edm
gmao
0.0.1-快照
战争
gmao
GMAO项目
org.springframework.boot
spring启动程序父级
1.5.8.1发布
UTF-8
UTF-8
1.8
org.springframework.boot
春靴起跑服
org.springframework.boot
spring引导启动器数据jpa
org.springframework.boot
弹簧启动装置
mysql
mysql连接器java
8.0.13
org.mariadb.jdbc
mariadb java客户端
1.5.7
org.springframework.boot
弹簧启动机tomcat
假如
org.springframework.boot
SpringBootStarterWeb
...
org.apache.httpcomponents
httpclient
4.5.3
...
com.google.zxing
核心
2
com.google.zxing
基础
2
org.springframework.boot
弹簧启动安全
org.springframework.boot
springbootmaven插件
但在运行时,CORS错误仍在发生

设置Spring安全性

 @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Invoke the cors(); method on HttpSecurity otherwise cors settings are not applied on http security
            http.cors();
            // further stuff
}
然后实现一个cors过滤器bean

 @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
如文档所述,调用http.cors()时将自动使用Bean。

设置Spring安全性

 @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Invoke the cors(); method on HttpSecurity otherwise cors settings are not applied on http security
            http.cors();
            // further stuff
}
然后实现一个cors过滤器bean

 @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

如文档所述,调用http.cors()时将自动使用Bean。

在实现Daniel的答案后,应将此代码添加到SecurityConfiguration类中:
http.csrf().disable()

实现Daniel的答案后,应将此代码添加到SecurityConfiguration类中:
http.csrf().disable()

您是如何在spring security上配置spring security和cors的?您能提供cors错误的详细信息吗?它说哪些cors头丢失或无效?您是如何在spring security上配置spring security和cors的?您能提供cors错误的详细信息吗?哪些cors头它是否表示缺少或无效?我应该将类
SecurityConfiguration
放在哪里?我应该把
CorsFilter
的实现放在哪里?我不知道你的项目结构,但你可以把SecurityConfig放在你喜欢的任何地方。例如,在名为
config
的包中。corsbean声明也是如此。您可以将其放入
@配置
类中,例如,我实现了您的答案,但错误仍在发生。我更新了我的帖子以包含代码。在实现您的答案后,应该将此代码添加到SecurityConfiguration类中:http.csrf().disable();对不起,我错过了要发布的内容!我应该将类
SecurityConfiguration
放在哪里?我应该把
CorsFilter
的实现放在哪里?我不知道你的项目结构,但你可以把SecurityConfig放在你喜欢的任何地方。例如,在名为
config
的包中。corsbean声明也是如此。您可以将其放入
@配置
类中,例如,我实现了您的答案,但错误仍在发生。我更新了我的帖子以包含代码。在实现您的答案后,应该将此代码添加到SecurityConfiguration类中:http.csrf().disable();对不起,我错过了要发布的内容!