首页 > 其他分享 >cors-filter过滤器解决跨域问题

cors-filter过滤器解决跨域问题

时间:2024-08-01 14:08:22浏览次数:8  
标签:跨域 true cors filter defaults CORS com

https://www.cnblogs.com/fanshuyao/

 

cors-filter为第三方组件。

一、官网地址

http://software.dzhuvinov.com/cors-filter.html

 

二、Springboot使用cors-filter

1、引入依赖

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.9</version>
</dependency>

2、配置类

复制代码
import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.thetransactioncompany.cors.CORSFilter;

/**
 * 使用配置方式开发Filter,否则其中的自动注入无效
 *
 * @author Chris.Liao
 */
@Configuration
public class HttpFilterConfig {

    /**
     * com.thetransactioncompany cors-filter
     * @return
     */
    @Bean
    public FilterRegistrationBean<Filter> corsFilter() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        
        registration.setFilter(new CORSFilter()); 
        
        //cors.supportsCredentials {true|false} defaults to true.
        //registration.addInitParameter("cors.supportsCredentials", "true");
        
        registration.addInitParameter("cors.allowOrigin", "http://127.0.0.1:7010,http://lqy.com:7010");//不符合时,报错:Cross-Origin Resource Sharing (CORS) Filter: CORS origin denied
        
        //cors.supportedMethods {method-list} defaults to "GET, POST, HEAD, OPTIONS".
        registration.addInitParameter("cors.supportedMethods", "GET,POST");//不符合时,报错:Cross-Origin Resource Sharing (CORS) Filter: Unsupported HTTP method
        
        //cors.supportedHeaders {"*"|header-list} defaults to *.
        //registration.addInitParameter("cors.supportedHeaders", "*");
        
        //cors.exposedHeaders {header-list} defaults to empty list.
        //registration.addInitParameter("cors.exposedHeaders", "");
        
        //cors.maxAge {int} defaults to -1 (unspecified).3600表示一个小时
        registration.addInitParameter("cors.maxAge", "3600");
        
        //cors.allowSubdomains {true|false} defaults to false.
        //cors.allowGenericHttpRequests {true|false} defaults to true.
        //cors.tagRequests {true|false} defaults to false (no tagging).
        
        registration.setName("CORSFilter"); //过滤器名称
        registration.addUrlPatterns("/*");//过滤路径
        registration.setOrder(1); //设置顺序
        return registration;
    }
}
复制代码

 

三、Spring Web应用使用cors-filter

1、引入Jar包(2个),放在项目的/WEB-INF/lib/目录下

cors-filter-2.9.jar

java-property-utils-1.13.jar

下载地址:

https://repo1.maven.org/maven2/com/thetransactioncompany/cors-filter/2.9/cors-filter-2.9.jar

https://repo1.maven.org/maven2/com/thetransactioncompany/java-property-utils/1.13/java-property-utils-1.13.jar

当前最新版为:2.9

 

2、在WEB-INF/web.xml配置过滤器

最简单的配置:

复制代码
<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
复制代码

 

带初始化参数的配置:

复制代码
<filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

        <init-param>
                <param-name>cors.allowOrigin</param-name>
                <param-value>http://example.com</param-value>
        </init-param>
</filter>

复制代码

 

四、cors-filter 初始化参数:

复制代码
cors.allowGenericHttpRequests

cors.allowOrigin

cors.allowSubdomains

cors.supportedMethods

cors.supportedHeaders

cors.exposedHeaders

cors.supportsCredentials

cors.maxAge

cors.tagRequests
复制代码

 

cors.allowGenericHttpRequests {true|false} defaults to true.

If true generic HTTP requests will be allowed to pass through the filter, else only valid and accepted CORS requests will be allowed (strict CORS filtering).

 

cors.allowOrigin {"*"|origin-list} defaults to *.
Whitespace-separated list of origins that the CORS filter must allow. Requests from origins not included here will be refused with an HTTP 403 "Forbidden" response. If set to * (asterisk) any origin will be allowed.

 

cors.allowSubdomains {true|false} defaults to false.
If true the CORS filter will allow requests from any origin which is a subdomain origin of the allowed origins. A subdomain is matched by comparing its scheme and suffix (host name / IP address and optional port number).

 

cors.supportedMethods {method-list} defaults to "GET, POST, HEAD, OPTIONS".
List of the supported HTTP methods. These are advertised through the Access-Control-Allow-Methods header and must also be implemented by the actual CORS web service. Requests for methods not included here will be refused by the CORS filter with an HTTP 405 "Method not allowed" response.

 

cors.supportedHeaders {"*"|header-list} defaults to *.
The names of the supported author request headers. These are advertised through the Access-Control-Allow-Headers header.

If the configuration property value is set to * (asterisk) any author request header will be allowed. The CORS Filter implements this by simply echoing the requested value back to the browser.

 

cors.exposedHeaders {header-list} defaults to empty list.
List of the response headers other than simple response headers that the browser should expose to the author of the cross-domain request through the XMLHttpRequest.getResponseHeader() method. The CORS filter supplies this information through the Access-Control-Expose-Headers header.

 

cors.supportsCredentials {true|false} defaults to true.
Indicates whether user credentials, such as cookies, HTTP authentication or client-side certificates, are supported. The CORS filter uses this value in constructing the Access-Control-Allow-Credentials header.

 

cors.maxAge {int} defaults to -1 (unspecified).
Indicates how long the results of a preflight request can be cached by the web browser, in seconds. If -1 unspecified. This information is passed to the browser via the Access-Control-Max-Age header.

 

cors.tagRequests {true|false} defaults to false (no tagging).
Enables HTTP servlet request tagging to provide CORS information to downstream handlers (filters and/or servlets).

 

 

总结:cors跨域请求解决方案(建议采用方案1)

1、springboot CORS 跨域请求解决三大方案,springboot CorsFilter解决跨域问题

https://www.cnblogs.com/fanshuyao/p/14030944.html

 

2、cors-filter使用,cors-filter解决跨域访问,cors-filter跨域请求

https://www.cnblogs.com/fanshuyao/p/14036848.html

 

3、org.ebaysf.web的cors-filter使用,cors-filter跨域请求

https://www.cnblogs.com/fanshuyao/p/14042293.html

 

4、java tomcat-catalina CorsFilter使用,apache tomcat-catalina CorsFilter使用

https://www.cnblogs.com/fanshuyao/p/14042420.html

 

5、springboot jsonp 跨域请求,springboot使用jsonp跨域

https://www.cnblogs.com/fanshuyao/p/14034014.html

 

https://www.cnblogs.com/fanshuyao/

标签:跨域,true,cors,filter,defaults,CORS,com
From: https://www.cnblogs.com/lvjinlin/p/18336529

相关文章

  • 阿里云设置跨域规则后调用OSS时仍然报No'Access-Control-Allow-Origin'的错误原因和解
    问题描述为了实现跨域访问,保证跨域数据传输的安全进行,在OSS控制台设置了跨域CORS规则后,通过SDK进行程序调用时报以下错误。No'Access-Control-Allow-Origin'headerispresentontherequestedresource问题原因出现跨域问题的原因如下:跨域CORS规则设置异常:未正确设......
  • 上传多个图像时 React 前端和 Flask 后端出现 CORS 策略错误
    实际上,我已经在reactJs中制作了前端,在pythonFlask中制作了后端(使用cnn模型进行一些预测)。当我按照我的请求发送5到6张图像时,它工作正常,但是当我发送10到15张图像和一些时间时令人筋疲力尽,然后它给出了类似的错误,尽管我在下面给出的代码中设置了Cors:192.168.151.24/:1Accesst......
  • js-数组内置函数-filter、map、forEach、reduce
    1、过滤数组-filter筛选数组元素,并生成新数组//过滤出分数为60分以上的数据<script>constarr=[{'name':'张三','score':80},{'name':'张六','score':50},{'name':'李四','score&#......
  • Filter过滤器
    1.导包点击查看代码<dependencies><!--Servlet依赖--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version&g......
  • Filter
    想在大风天去见你,把我吹进你的怀里。--zhu切面编程1、AOP:AspectOrientedProgramming的缩写,意为面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP思想的延续。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的......
  • SciTech-BigDataAIML-Python Time Series Handbook - Kalman filter: 卡尔曼滤波器算
    网上文档:Python时间序列手册:有ipynb和PDF文件:https://filippomb.github.io/python-time-series-handbook/notebooks/07/kalman-filter.htmlMITPDF:AnIntroductiontotheKalmanFilter-MITIllinoisUniversityPDF:UnderstandingtheBasisoftheKalmanF......
  • 面试必考:全面解析跨域及其解决方案
    跨域问题是前端开发中常见且必须掌握的知识点之一。本文将详细介绍跨域的概念、手写JSONP和CORS跨域代码及其原理,如何在Vue3项目中替换Mock数据接口为真实后端数据接口,以及总结九种常见的跨域解决方案。一、什么是跨域?跨域是指浏览器因同源策略的限制,无法访问不同源(协议、域名、......
  • forms.ModelMultipleChoiceField 与 widget=FilteredSelectMultiple 不适用于自定义新
    我试图在自定义的新管理表单页面上显示forms.ModelMultipleChoiceField但它似乎没有像在已经制作的Django页面上显示的方式显示,例如模型产品Django管理页面。我的forms.ModelMultipleChoiceField看起来像这样:显示我的forms.ModelMultipleChoiceField是什么样子......
  • 具有 ParameterFilter 选项和 Contains 的 AWS ssm describe_parameters 返回结果,但具
    我在从aws参数存储获取数据时遇到一个奇怪的问题。我正在调用描述参数来获取有关参数的信息。下面是相同的Python代码。参数存储:my-data.api_dataimportboto3ssm_client=boto3.client('ssm')response=ssm_client.describe_parameters(ParameterFilters=[......
  • springboot解决跨域问题
    在SpringBoot中解决跨域问题(CORS,Cross-OriginResourceSharing)有多种方法。这里介绍几种常用的方法:方法一:使用全局配置可以在SpringBoot的配置类中使用WebMvcConfigurer接口来配置全局的CORS策略。importorg.springframework.context.annotation.Bean;importorg.sprin......