springboot项目实现配置跨域

 更新时间:2024年09月05日 08:59:05   作者:wangpeng1201  
这篇文章主要介绍了springboot项目实现配置跨域问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

在Spring Boot项目中配置跨域(CORS,Cross-Origin Resource Sharing)主要是为了允许来自不同源(不同的协议、域名或端口)的前端应用能够访问后端API。

Spring Boot提供了多种方式来配置跨域支持。

1. 使用@CrossOrigin注解

最简单的方式是在控制器或者具体的方法上使用@CrossOrigin注解。

例如:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://example.com") // 允许来自 http://example.com 的跨域请求
public class MyController {

    @GetMapping("/myEndpoint")
    public String myMethod() {
        return "Hello, World!";
    }
}

这将允许来自http://example.com的跨域请求访问/myEndpoint这个接口。

2. 全局跨域配置

如果你想要为整个应用配置跨域支持,可以在配置类中添加一个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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 为所有请求添加跨域支持
                .allowedOrigins("*")    // 允许任何源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法
                .allowCredentials(true); // 是否允许发送Cookie信息
    }
}

这个配置将允许任何源的跨域请求,并且允许GETPOSTPUTDELETE方法。

allowCredentials设置为true表示允许客户端发送Cookie信息。

3. 使用CorsFilter

如果需要更细致的控制,可以创建一个CorsFilter并注册为Bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins("*");
        configuration.setAllowedMethods("GET", "POST", "PUT", "DELETE");
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(source);
    }
}

这个配置与上面的全局跨域配置类似,但是通过CorsFilter提供了更多的灵活性和控制。

注意事项:

  • allowedOrigins可以是一个具体的域名,如"http://example.com",或者使用"*"来允许任何源。
  • allowedMethods定义了允许的HTTP方法。
  • allowCredentials设置为true时,服务器将接受包含敏感信息(如Cookies和HTTP认证信息)的跨域请求。
  • allowedHeaders定义了允许的HTTP请求头。

根据你的项目需求和安全考虑,合理配置跨域支持是非常重要的。

在生产环境中,通常不建议允许任何源("*"),而是应该明确指定可信的源。

当然,除了上述提到的使用@CrossOrigin注解、全局跨域配置和CorsFilter之外,还有其他一些方法可以在Spring Boot项目中配置跨域支持。

4. 配置WebMvcConfigurerProperties

在Spring Boot中,可以通过扩展WebMvcConfigurerProperties类来配置跨域。

首先,需要创建一个配置类并继承WebMvcConfigurerProperties

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsConfig implements WebMvcConfigurer {

    private String[] allowedOrigins;
    private String[] allowedMethods;
    private String[] allowedHeaders;
    private boolean allowCredentials;

    // getters and setters ...

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins)
                .allowedMethods(allowedMethods)
                .allowedHeaders(allowedHeaders)
                .allowCredentials(allowCredentials);
    }
}

然后,在application.propertiesapplication.yml中添加相应的配置:

# application.properties
cors.allowedOrigins[0]=http://example.com
cors.allowedMethods[0]=GET
cors.allowedMethods[1]=POST
cors.allowedHeaders[0]=Content-Type
cors.allowCredentials=true

5. 使用Spring Security

如果你的项目中使用了Spring Security,可以通过配置HttpSecurity来实现跨域支持。

首先,需要创建一个配置类并重写configure(HttpSecurity http)方法:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...其他配置...
            .cors().and() // 启用默认的跨域配置
            // ...其他配置...
    }
}

如果需要自定义跨域配置,可以使用.cors()方法并传递一个CorsConfigurationSource实例:

 CorsConfiguration configuration = new CorsConfiguration();
 configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
 configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE"));
 configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
 configuration.setAllowCredentials(true);

 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
 source.registerCorsConfiguration("/**", configuration);

 http.cors(source).and();

6. 使用第三方库

还可以使用第三方库如cors-filter来实现跨域支持。

这通常需要在项目的pom.xml中添加依赖,并在web.xml中配置过滤器。

以上是一些在Spring Boot项目中配置跨域支持的方法。

选择最适合项目需求和架构的方法,并确保考虑到安全性和性能的影响。

在实施跨域策略时,应当避免过度宽松的配置,以免引入安全风险。

这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 深入理解happens-before和as-if-serial语义

    深入理解happens-before和as-if-serial语义

    本文大部分整理自《Java并发编程的艺术》,温故而知新,加深对基础的理解程度。下面可以和小编来一起学习下
    2019-05-05
  • Java实现字符串拆分的三种方法详解

    Java实现字符串拆分的三种方法详解

    字符串拆分,看似简单的操作,背后却隐藏着性能的玄机,本文将和大家详细介绍一下三种Java实现字符串拆分的方法,有需要的小伙伴可以参考一下
    2026-02-02
  • Mybatis Plugin拦截器开发过程详解

    Mybatis Plugin拦截器开发过程详解

    这篇文章主要介绍了Mybatis Plugin拦截器开发过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • Java 18 新特性之Web服务器 jwebserver功能

    Java 18 新特性之Web服务器 jwebserver功能

    JEP 408: Simple Web Server,是这次Java 18推出的一个比较独立的全新功能点。我们可以通过命令行工具来启动一个提供静态资源访问的迷你Web服务器,本文通过一个构建HTML页面的例子,来尝试一下jwebserver的功能
    2022-04-04
  • Java SpringBoot 集成 Redis详解

    Java SpringBoot 集成 Redis详解

    Redis 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API
    2021-10-10
  • Java LinkedList集合功能实例解析

    Java LinkedList集合功能实例解析

    这篇文章主要介绍了Java LinkedList集合功能实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • SpringBoot中使用Redis对接口进行限流的实现

    SpringBoot中使用Redis对接口进行限流的实现

    本文将结合实例代码,介绍SpringBoot中使用Redis对接口进行限流的实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • 如何在JAVA中使用Synchronized

    如何在JAVA中使用Synchronized

    这篇文章主要介绍了如何在JAVA中使用Synchronized,文中代码非常详细,对大家的学习有所帮助,感兴趣的朋友可以参考下
    2020-06-06
  • Java中Object和内部类举例详解

    Java中Object和内部类举例详解

    这篇文章主要介绍了Java中Object和内部类的相关资料,Object类是Java中所有类的父类,提供了toString、hashCode和equals等方法,内部类分为实例内部类、静态内部类、匿名内部类和局部内部类,需要的朋友可以参考下
    2025-05-05
  • MyBatis使用annonation定义类型映射的简易用法示例

    MyBatis使用annonation定义类型映射的简易用法示例

    这篇文章主要介绍了MyBatis使用annonation定义类型映射的简易用法示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09

最新评论