本文内容引用自:

https://howtodoinjava.com/spring5/webmvc/spring-mvc-cors-configuration/

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

  • 基本概念

   跨源资源共享(Cross-Origin Resource Sharing, CORS)是一种机制,它使用额外的HTTP头文件告诉浏览器,让在一个源(域)运行的web应用程序有权访问来自不同源服务器的选定资源。当web应用程序请求源(域、协议和端口)与自己的源不同的资源时,它将执行跨源HTTP请求。

  • 跨源请求的示例:

     来自http://domain-a.com的Web应用程序的前端JavaScript代码使用XMLHttpRequest来请求http://api.domain-b.com/data.json 。

  • 安全策略

     出于安全原因,浏览器限制从脚本内发起的跨源HTTP请求。例如,XMLHttpRequest提取API遵循同源策略。这意味着使用这些API的Web应用程序只能从加载应用程序的同一源请求HTTP资源,除非来自其他来源的响应包含正确的CORS标头。

  • implementation in Spring

  

1. Spring CORS – Method level with @CrossOrigin

Spring MVC provides @CrossOrigin annotation. This annotation marks the annotated method or type as permitting cross origin requests.

1.1. Spring CORS allow all

By default, @CrossOrigin allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes.

You can override default CORS settings by giving value to annotation attributes :

ATTRIBUTE DESCRIPTION
origins List of allowed origins. It’s value is placed in the Access-Control-Allow-Origin header of both the pre-flight response and the actual response.
– – means that all origins are allowed.
– If undefined, all origins are allowed.
allowedHeaders List of request headers that can be used during the actual request. Value is used in preflight’s response header Access-Control-Allow-Headers.
– – means that all headers requested by the client are allowed.
– If undefined, all requested headers are allowed.
methods List of supported HTTP request methods. If undefined, methods defined by RequestMapping annotation are used.
exposedHeaders List of response headers that the browser will allow the client to access. Value is set in actual response header Access-Control-Expose-Headers.
– If undefined, an empty exposed header list is used.
allowCredentials It determine whether browser should include any cookies associated with the request.
– false – cookies should not included.
– "" (empty string) – means undefined.
– true – pre-flight response will include the header Access-Control-Allow-Credentials with value set to true.
– If undefined, credentials are allowed.
maxAge maximum age (in seconds) of the cache duration for pre-flight responses. Value is set in header Access-Control-Max-Age.
– If undefined, max age is set to 1800 seconds (30 minutes).

1.2. @CrossOrigin at Class/Controller Level

HomeController.java
@CrossOrigin(origins = "*", allowedHeaders = "*")
@Controller
public class HomeController
{
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

Read More – Spring 5 MVC Example

1.3. @CrossOrigin at Method Level

HomeController.java
@Controller
public class HomeController
{
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

1.4. @CrossOrigin Overridden at Method Level

homeInit() method will be accessible only from domain http://example.com. Rest other methods in HomeController will be accessible from all domains.

HomeController.java
@Controller
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class HomeController
{
    @CrossOrigin(origins = "http://example.com")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

2. Spring CORS – Global CORS configuration

2.1. Spring MVC CORS with WebMvcConfigurerAdapter

To enable CORS for the whole application, use WebMvcConfigurerAdapter to add CorsRegistry.

CorsConfiguration.java
@Configuration
@EnableWebMvc
public class CorsConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET""POST");
    }
}

2.2. Spring Boot CORS with WebMvcConfigurer

In spring boot application, it is recommended to just declare a WebMvcConfigurer bean.

CorsConfiguration.java
@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

2.3. CORS with Spring Security

To enable CORS support through Spring security, configure CorsConfigurationSource bean and use HttpSecurity.cors() configuration.

WebSecurityConfig.java
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            //other config
    }
 
    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

出于安全原因,浏览器限制从脚本内发起的跨源HTTP请求。例如,XMLHttpRequest提取API遵循同源策略。这意味着使用这些API的Web应用程序只能从加载应用程序的同一源请求HTTP资源,除非来自其他来源的响应包含正确的CORS标头。

跨源资源共享(CORS)概念、实现(用Spring)、起源介绍的更多相关文章

  1. AmazonS3 使用AWS SDK for Java实现跨源资源共享 (CORS)

    CORS 配置 创建 CORS 配置并对存储桶设置该配置 通过添加规则来检索并修改配置 向存储桶添加修改过的配置 删除配置 import com.amazonaws.AmazonServiceExce ...

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

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

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

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

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

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

  5. SpringBoot系列——CORS(跨源资源共享)

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

  6. VUE SpringCloud 跨域资源共享 CORS 详解

    VUE  SpringCloud 跨域资源共享 CORS 详解 作者:  张艳涛 日期: 2020年7月28日 本篇文章主要参考:阮一峰的网络日志 » 首页 » 档案 --跨域资源共享 CORS 详解 ...

  7. 跨域资源共享(CORS)问题解决方案

    CORS:Cross-Origin Resource Sharing(跨域资源共享) CORS被浏览器支持的版本情况如下:Chrome 3+.IE 8+.Firefox 3.5+.Opera 12+. ...

  8. 跨域资源共享CORS与JSONP

    同源策略限制: 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说 ...

  9. JavaScript跨源资源共享

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

随机推荐

  1. 复旦大学2017--2018学年第一学期高等代数I期末考试情况分析

    一.期末考试成绩班级前十名 郭宇城(100).魏一鸣(93).乔嘉玮(92).刘宇其(90).朱柏青(90).王成文健(90).方博越(88).熊子恺(88).张君格(88).崔镇涛(87).史书珣( ...

  2. U3D外包团队—技术分享 U3d中获得物体的size

    以size的x方向为例 1:gameObject.renderer.bounds.size.x;//这个值的结果真实反应出有MeshRenderer这个组件的模型的尺寸.不需要再乘以localScal ...

  3. Codeforces 40 E. Number Table

    题目链接:http://codeforces.com/problemset/problem/40/E 妙啊... 因为已经确定的格子数目严格小于了$max(n,m)$,所以至少有一行或者一列是空着的, ...

  4. docker 安装mysql示例

    docker pull mysql 错误的启动: [root@localhost ~]# docker run --name mysql01 -d mysql 42f09819908bb72dd99a ...

  5. HTML 点击图片放大

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. stylus笔记(二)

    1.方法 函数  Stylus强大之处就在于其内置的语言函数定义.其定义与混入(mixins)一致:却可以返回值. 默认参数 可选参数往往有个默认的给定表达.在Stylus中,我们甚至可以超越默认参数 ...

  7. 一个简单CI/CD流程的思考

    因为公司有两地研发团队,在统一CI/CD上难度不亚于两家公司合并后的新流程建立,并非不可攻克,简单描述下心得. 首先,代码管理使用gerrit -> 因其强大的 codereview 功能被选中 ...

  8. js验证银行卡号 luhn校验规则

    <script type="text/javascript"> //luhn校验规则:16位银行卡号(19位通用): // 1.将未带校验位的 15(或18)位卡号从右 ...

  9. SpringBoot使用CORS解决跨域请求问题

    什么是跨域? 同源策略是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 如果一个请求地址里面的协议.域名和端口号都相同,就属于同源. ...

  10. chrome扩展应用API

    background scripts可以访问所有的 WebExtension JavaScript APIs ,但是不能直接访问页面 content scripts 可以通过标准的DOM api 读取 ...