前言

  出于安全原因,浏览器禁止ajax调用当前源之外的资源(同源策略),我们之前也有写个几种跨域的简单实现(还在问跨域?本文记录js跨域的多种实现实例),本文主要详细介绍CORS,跨源资源共享,以及如何在SpringBoot的几种实现方式

  这里主要参考spring的这篇:https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/web.html#mvc-cors

  以及:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

  CORS介绍

  跨源资源共享(Cross-Origin Resource Sharing, CORS)是由大多数浏览器实现的W3C规范,它允许指定授权了哪种跨域请求,而不是使用基于IFRAME(内嵌框架)或JSONP的不太安全且功能不太强大的方法。  

  CORS分为简单请求非简单请求两种跨域请求方式,Spring MVC HandlerMapping的实现提供了对CORS的内置支持。成功地将请求映射到处理程序之后,HandlerMapping的实现将检查CORS配置并不同的请求进行操作:预检请求直接处理,而简单请求和非简单请求被拦截、验证,并设置了所需的CORS响应头。为了启用跨源请求,您需要一些显式声明的CORS配置。如果没有找到匹配的CORS配置,预检请求将被拒绝。没有将CORS标头添加到简单、非简单CORS请求的响应中,浏览器会拒绝这个跨域请求。

  简单请求不会触发预检请求,而非简单请求在发起之前会先发起预检请求,以获知服务器是否允许该实际请求,"预检请求“的使用,可以避免跨域请求对服务器的用户数据产生未预期的影响。

  跨域响应字段含义:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS#HTTP_%E5%93%8D%E5%BA%94%E9%A6%96%E9%83%A8%E5%AD%97%E6%AE%B5

  跨域请求字段含义:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS#HTTP_%E8%AF%B7%E6%B1%82%E9%A6%96%E9%83%A8%E5%AD%97%E6%AE%B5

  简单请求

  若请求满足所有下述条件,则该请求可视为“简单请求”:

  • 使用下列方法之一:

    • GET
    • HEAD
    • POST
  • Fetch 规范定义了对 CORS 安全的首部字段集合,不得人为设置该集合之外的其他首部字段。该集合为:
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type (需要注意额外的限制)
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  • Content-Type 的值仅限于下列三者之一:
    • text/plain
    • multipart/form-data
    • application/x-www-form-urlencoded
  • 请求中的任意XMLHttpRequestUpload 对象均没有注册任何事件监听器;XMLHttpRequestUpload 对象可以使用 XMLHttpRequest.upload 属性访问。
  • 请求中没有使用 ReadableStream 对象。

  例如:

  非简单请求

  当请求满足下述任一条件时,即视为非简单请求,应首先发送预检请求:

  • 使用了下面任一 HTTP 方法:

    • PUT
    • DELETE
    • CONNECT
    • OPTIONS
    • TRACE
    • PATCH
  • 人为设置了对 CORS 安全的首部字段集合之外的其他首部字段。该集合为:
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type (需要注意额外的限制)
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  • Content-Type 的值不属于下列之一:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  • 请求中的XMLHttpRequestUpload 对象注册了任意多个事件监听器。
  • 请求中使用了ReadableStream对象。

  例如:  

  PS:如果ajax的contentType:"application/json;charset=UTF-8",设置成了json格式传输,那么你的data就要这样传JSON.stringify({id:1}),并且后端接参要加上@RequestBody,用对象去接MVC会帮我们自动注入参数,用字符串去接,会得到json字符串

  附带身份凭证的请求

  CORS 的一个有趣的特性是,可以基于  HTTP cookies 和 HTTP 认证信息发送身份凭证。一般而言,对于跨域 XMLHttpRequest请求,浏览器不会发送身份凭证信息。如果要发送凭证信息,需要设置 XMLHttpRequest的某个特殊标志位 withCredentials=true,就可以向服务器发送Cookies,但是,如果服务器端的响应中未携带 Access-Control-Allow-Credentials: true,浏览器将不会把响应内容返回给请求的发送者。

  如果前端设置了true,后端为false,则会

  实现方式

  PS:不管是哪种方法,一定要看仔细前端的请求头中Origins的值到底是什么,前端的值与后端配置的值对应不上则无法跨域,比如前端是http://localhost:8080,而后端配置成IP,则无法跨域

  @CrossOrigin

  TestController接口测试

package cn.huanzi.qch.springbootcors.controller;

import org.springframework.web.bind.annotation.*;

@RequestMapping("cors/")
@RestController
public class TestController {
/*
通过注解配置CORS跨域测试
$.ajax({
type:"POST",
url:"http://localhost:10095/cors/corsByAnnotation",
data:{id:1},
dataType:"text",//因为我们响应的是不是json,这里要改一下
contentType:"application/x-www-form-urlencoded",
//contentType:"application/json;charset=UTF-8",//如果用这个,则为非简单请求
xhrFields:{ withCredentials:true },
success:function(data){
console.log(data);
},
error:function(data){
console.log("报错啦");
}
})
*/
@CrossOrigin(
origins = "https://www.cnblogs.com",
allowedHeaders = "*",
methods = {RequestMethod.POST},
allowCredentials = "true",
maxAge = 3600
)
@PostMapping("corsByAnnotation")
public String corsByAnnotation(String id) {
return "corsByAnnotation," + id;
}
}

  如果@CrossOrigin注解在controller类上面声明,则整个controller类的接口都可以跨域调用

  配置Config

  Java Configuration

  MyConfiguration配置类

package cn.huanzi.qch.springbootcors.config;

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 MyConfiguration { @Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/cors/corsByConfig")
.allowedOrigins("https://www.cnblogs.com")
.allowedMethods("POST")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
};
}
}

  TestController接口测试

package cn.huanzi.qch.springbootcors.controller;

import org.springframework.web.bind.annotation.*;

@RequestMapping("cors/")
@RestController
public class TestController {
/*
通过Config配置CORS跨域测试
$.ajax({
type:"POST",
url:"http://localhost:10095/cors/corsByConfig",
data:{id:2},
dataType:"text",//因为我们响应的是不是json,这里要改一下
contentType:"application/x-www-form-urlencoded",
//contentType:"application/json;charset=UTF-8",//如果用这个,则为非简单请求
xhrFields:{ withCredentials:true },
success:function(data){
console.log(data);
},
error:function(data){
console.log("报错啦");
}
})
*/
@PostMapping("corsByConfig")
public String corsByConfig(String id) {
return "corsByConfig," + id;
}
}

  XML Configuration

  xml格式我就不试了,大家看文档就好了:https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/web.html#mvc-cors-global-xml

  CORS Filter

  配置拦截器在启动项目的时候会报一个bean已存在,叫我们改名或启用覆盖默认bean

Description:

The bean 'myCorsFilter', defined in null, could not be registered. A bean with that name has already been defined in file [C:\Users\Administrator\Desktop\杂七杂八\springBoot\springboot-cors\target\classes\cn\huanzi\qch\springbootcors\filter\MyCorsFilter.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

  配置覆盖

#启用覆盖默认bean
spring.main.allow-bean-definition-overriding=true

  MyCorsFilter

package cn.huanzi.qch.springbootcors.filter;

import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List; @Component
@ServletComponentScan
@WebFilter(filterName = "myCorsFilter", //过滤器名称
urlPatterns = "/cors/corsByMyCorsFilter",//url路径
initParams = {
@WebInitParam(name = "allowOrigin", value = "https://www.cnblogs.com"),//允许的请求源,可用,分隔,*表示所有
@WebInitParam(name = "allowMethods", value = "POST"),//允许的请求方法,可用,分隔,*表示所有
@WebInitParam(name = "allowCredentials", value = "true"),
@WebInitParam(name = "allowHeaders", value = "*"),
@WebInitParam(name = "maxAge", value = "3600"),//60秒 * 60,相当于一个小时
})
public class MyCorsFilter implements Filter { private String allowOrigin;
private String allowMethods;
private String allowCredentials;
private String allowHeaders;
private String maxAge; @Override
public void init(FilterConfig filterConfig) {
//读取@WebFilter的initParams
allowOrigin = filterConfig.getInitParameter("allowOrigin");
allowMethods = filterConfig.getInitParameter("allowMethods");
allowCredentials = filterConfig.getInitParameter("allowCredentials");
allowHeaders = filterConfig.getInitParameter("allowHeaders");
maxAge = filterConfig.getInitParameter("maxAge");
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (!StringUtils.isEmpty(allowOrigin)) {
if (allowOrigin.equals("*")) {
response.setHeader("Access-Control-Allow-Origin", allowOrigin);
} else {
List<String> allowOriginList = Arrays.asList(allowOrigin.split(","));
if (allowOriginList.size() > 0) {
//如果来源在允许来源内
String currentOrigin = request.getHeader("Origin");
if (allowOriginList.contains(currentOrigin)) {
response.setHeader("Access-Control-Allow-Origin", currentOrigin);
}
}
}
}
if (!StringUtils.isEmpty(allowMethods)) {
response.setHeader("Access-Control-Allow-Methods", allowMethods);
}
if (!StringUtils.isEmpty(allowCredentials)) {
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
}
if (!StringUtils.isEmpty(allowHeaders)) {
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
}
if (!StringUtils.isEmpty(maxAge)) {
response.setHeader("Access-Control-Max-Age", maxAge);
} //执行
filterChain.doFilter(servletRequest, servletResponse);
} @Override
public void destroy() { }
}

  TestController接口测试

package cn.huanzi.qch.springbootcors.controller;

import org.springframework.web.bind.annotation.*;

@RequestMapping("cors/")
@RestController
public class TestController {/*
通过拦截器配置CORS跨域测试
$.ajax({
type:"POST",
url:"http://localhost:10095/cors/corsByMyCorsFilter",
data:{id:3},
dataType:"text",//因为我们响应的是不是json,这里要改一下
contentType:"application/x-www-form-urlencoded",
//contentType:"application/json;charset=UTF-8",//如果用这个,则为非简单请求
xhrFields:{ withCredentials:true },
success:function(data){
console.log(data);
},
error:function(data){
console.log("报错啦");
}
})
*/
@PostMapping("corsByMyCorsFilter")
public String corsByMyCorsFilter(String id) {
return "corsByMyCorsFilter," + id;
}
}

  测试

  打开博客园,F12打开控制台,开始测试

  注解

  java配置

  corsFilter

  后记

  暂时记录到这里

  代码开源

  代码已经开源、托管到我的GitHub、码云:

  GitHub:https://github.com/huanzi-qch/springBoot

  码云:https://gitee.com/huanzi-qch/springBoot

SpringBoot系列——CORS(跨源资源共享)的更多相关文章

  1. 彻底掌握CORS跨源资源共享

    本文来自于公众号链接: 彻底掌握CORS跨源资源共享 ) 本文接上篇公众号文章:彻底理解浏览器同源策略SOP 一.概述 在云时代,各种SAAS应用层出不穷,各种互联网API接口越来越丰富,H5技术在微 ...

  2. CORS跨源资源共享概念及配置(Kubernetes Ingress和Spring Cloud Gateway)

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 跨源资源共享CORS 跨源资源共享 (CORS) (或通俗地译为跨域资源共享)是一种基于HTTP 头的机制,该机制通过 ...

  3. JavaScript跨源资源共享

    CORS(跨 源资源共享)基本思想,就是使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应式应该成功还是失败 IE对CORS的实现 IE8引入了XDR类型,与XHR类似,但可以实现安 ...

  4. 跨源资源共享(CORS)概念、实现(用Spring)、起源介绍

    本文内容引用自: https://howtodoinjava.com/spring5/webmvc/spring-mvc-cors-configuration/ https://developer.m ...

  5. CORS跨域资源共享你该知道的事儿

    "唠嗑之前,一些客套话" CORS跨域资源共享,这个话题大家一定不陌生了,吃久了大转转公众号的深度技术好文,也该吃点儿小米粥溜溜胃里的缝儿了,今天咱们就再好好屡屡CORS跨域资源共 ...

  6. 在ASP.NET Web API中实现CORS(跨域资源共享)

    默认情况下,是不允许网页从不同的域访问服务器资源的,访问遵循"同源"策略的原则. 会遇到如下的报错: XMLHttpRequest cannot load http://local ...

  7. JS高程3:Ajax与Comet-进度事件、跨源资源共享

    有以下 6 个进度事件  loadstart:在接收到响应数据的第一个字节时触发.  progress:在接收响应期间持续不断地触发.  error:在请求发生错误时触发.  abort:在因 ...

  8. CORS跨域资源共享漏洞

    CORS漏洞其中已经存在很久了,但是国内了解的人不是很多,文章更是少只有少,漏洞平台也没有此分类. 在DefConChina之后写了一篇算是小科普的文章. 定义CORS,Cross-Origin Re ...

  9. 跨域漏洞丨JSONP和CORS跨域资源共享

    进入正文之前,我们先来解决个小问题,什么是跨域? 跨域:指的是浏览器不能执行其它网站的脚本,它是由浏览器的同源策略造成的,是浏览器的安全限制! 跨域常见的两种方式,分别是JSONP和CORS. 今天i ...

随机推荐

  1. HALCON 光圈和景深的关系

    光圈越大,越亮,景深越小 光圈越小,越暗,景深越大 景深为成像清晰的那个范围

  2. WPF 中style文件的引用

    原文:WPF 中style文件的引用 总结一下WPF中Style样式的引用方法: 一,内联样式: 直接设置控件的Height.Width.Foreground.HorizontalAlignment. ...

  3. 投资人的能量往往大多远远不仅于此,他能站在不同的角度和高度看问题(要早点拿投资,要舍得让出股份)——最好不要让 Leader 一边做技术、一边做管理,人的能力是有限的,精力也是有限的

      摘要:在创业三年时间里作为联合创始人,虽然拿着大家均等的股份,我始终是没有什么话语权的,但是,这也给了我从旁观者的角度看清整个局面的机会.创业公司的成败绝大程度取决于技术大牛和公司 Leader, ...

  4. 在DELPHI中*.wav 文件怎么加到资源文件中

    比较“流行”的说法是:“16位的Delphi   1.0和32位的Delphi2.0.3.0都提供了资源         编译工具,其中   Delphi   1.0的资源编译器叫BRCC.EXE,D ...

  5. 了解Service

    多线程编程: 线程的基本用法: 1. class MyThread extends Thread{ @Override public void run() { //处理具体逻辑 } } new MyT ...

  6. 树莓派中安装QT

    树莓派中安装QT 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 环境: 主机:WIN7 硬件:树莓派 步骤: 参考链接:http://qt-proje ...

  7. SAP TABLECONTROL 自定义SEARCH HELP

    项目上需要开发一个界面如下的应用程序.这是一个MB1A发料的辅助程序,限制住移动类型和在特定字段写入产品号. 这个应用程序的主要功能毫无疑问是通过BAPI实现的.但在TABLECONTROL中需要对填 ...

  8. Laravel:php artisan key:generate三种报错解决方案,修改默认PHP版本(宝塔面板)

    为了兼容N多个网站,服务器上有3个PHP版本5.3/5.6/7.2.宝塔默认为5.3,但是laravel5.7并不支持,所以在创建线上 .env 环境配置文件,初始化应用配置时候报错了. cp .en ...

  9. Redis 学习笔记(篇一):字符串和链表

    本次学习除了基本内容之外主要思考三个问题:why(为什么).what(原理是什么).which(同类中还有哪些类似的东西,相比有什么区别). 由于我对 java 比较熟悉,并且 java 中也有字符串 ...

  10. Android项目开发之--------地铁时光机(一,搭建主框架)

    一:先看一下框架搭建后的效果图      , 二:框架结构 (1)底部导航栏采用的是: MainActivity(主框架), MsgFragment(首页), HistoryFragment(历史清单 ...