springboot处理跨域的方式
1. 基本知识
跨域指的是在一个域下的网页试图访问另一个域下的资源
由于浏览器的同源策略,默认情况下,javascript 只能在相同的域中进行请求
跨域通常涉及以下概念:
origin
: 包括协议、域名和端口号
比如 http://example.com:80same-origin policy
: 浏览器的安全策略,限制一个源的文档或脚本如何能与另一个源的资源进行交互cors
: 允许跨域请求的机制
服务器通过设置特定的响应头来告知浏览器哪些源是允许访问的
在 spring boot 中,处理跨域的方式有几种,以下是主要的几种方式:
- 使用 @crossorigin 注解: 这种方式较为简单,适用于控制器层
- 配置全局跨域设置: 这种方式适用于全局配置,可以在 web 配置类中设置
- 自定义 corsconfiguration: 适用于更复杂的跨域配置需求,可以在配置类中自定义
以下为demo示例
2. @crossorigin
可以在控制器类或方法上添加 @crossorigin 注解
注解的参数可以配置允许的源(origins)、允许的请求方法(methods)、允许的请求头(allowedheaders)、是否允许凭证(allowcredentials)等
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; @restcontroller @requestmapping("/api") public class mycontroller { @crossorigin(origins = "http://example.com") @getmapping("/data") public string getdata() { return "data from server"; } }
如果不使用 @crossorigin 注解,浏览器会阻止跨域请求,因为默认的同源策略不允许不同源之间的请求
3. 全局跨域设置
配置 webmvcconfigurer 来全局设置跨域
import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.config.annotation.corsregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigurer; /** * 配置类,用于全局设置 cors(跨域资源共享)配置 */ @configuration public class webconfig implements webmvcconfigurer { /** * 配置跨域请求的映射规则 * * @param registry 用于注册 cors 配置的注册表 */ @override public void addcorsmappings(corsregistry registry) { // 添加跨域映射规则 registry.addmapping("/**") // 允许所有路径的跨域请求 .allowedorigins("http://example.com") // 允许来自 http://example.com 的跨域请求 .allowedmethods("get", "post", "put", "delete") // 允许的请求方法 .allowedheaders("*") // 允许所有请求头 .allowcredentials(true); // 允许携带凭证(如 cookies) } }
4. 自定义 corsconfiguration
import org.springframework.context.annotation.bean; 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 customcorsconfig implements webmvcconfigurer { @bean public corsconfigurationsource corsconfigurationsource() { corsconfiguration configuration = new corsconfiguration(); configuration.setallowedorigins(arrays.aslist("http://example.com")); configuration.setallowedmethods(arrays.aslist("get", "post", "put", "delete")); configuration.setallowedheaders(arrays.aslist("*")); configuration.setallowcredentials(true); urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource(); source.registercorsconfiguration("/**", configuration); return source; } }
5. 实战
以下展示项目中的跨域
用 @autoconfiguration 进行自动配置
实现webmvcconfigurer 接口,并通过 filterregistrationbean 注册自定义的跨域过滤器 corsfilter 和其他过滤器
import org.springframework.boot.autoconfigure.autoconfiguration; import org.springframework.boot.autoconfigure.condition.conditionalonproperty; import org.springframework.boot.web.servlet.filterregistrationbean; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.filter.corsfilter; import org.springframework.web.servlet.config.annotation.webmvcconfigurer; import org.springframework.web.cors.corsconfiguration; import org.springframework.web.cors.urlbasedcorsconfigurationsource; @configuration @autoconfiguration @enableconfigurationproperties(webproperties.class) public class webautoconfiguration implements webmvcconfigurer { /** * 创建一个 corsfilter 过滤器的 bean,配置跨域设置 * * @return 配置了跨域设置的 filterregistrationbean */ @bean public filterregistrationbean<corsfilter> corsfilterbean() { // 创建 corsconfiguration 对象 corsconfiguration config = new corsconfiguration(); config.setallowcredentials(true); // 允许携带凭证(如 cookies) config.addallowedoriginpattern("*"); // 允许所有来源的请求(注意:生产环境中通常不建议使用 *,应具体配置允许的域) config.addallowedheader("*"); // 允许所有请求头 config.addallowedmethod("*"); // 允许所有 http 方法(get, post, put, delete 等) // 创建 urlbasedcorsconfigurationsource 对象 urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource(); source.registercorsconfiguration("/**", config); // 对所有路径配置跨域设置 // 创建并返回一个 filterregistrationbean 实例,注册 corsfilter return createfilterbean(new corsfilter(source), integer.min_value); } /** * 创建 demofilter bean,演示模式 * * @return 配置了 demofilter 的 filterregistrationbean */ @bean @conditionalonproperty(value = "demo", havingvalue = "true") public filterregistrationbean<demofilter> demofilter() { // 创建并返回一个 filterregistrationbean 实例,注册 demofilter return createfilterbean(new demofilter(), integer.min_value); } /** * 创建 filterregistrationbean 实例的通用方法 * * @param filter 需要注册的过滤器实例 * @param order 过滤器的执行顺序 * @return 配置了过滤器的 filterregistrationbean 实例 */ public static <t extends filter> filterregistrationbean<t> createfilterbean(t filter, integer order) { filterregistrationbean<t> bean = new filterregistrationbean<>(filter); bean.setorder(order); // 设置过滤器的顺序 return bean; } }
总结
处理方式 | 适用场景 | 配置位置 | 灵活性 | 配置难度 |
---|---|---|---|---|
@crossorigin 注解 | 单个控制器或方法 | 控制器层 | 低 | 低 |
全局配置(webmvcconfigurer) | 全局设置 | 配置类(webconfig) | 中 | 中 |
自定义 corsconfiguration | 复杂跨域需求 | 配置类(customcorsconfig) | 高 | 高 |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论