SpringBoot Web 配置CORS跨域解决方式

方式一:Tomcat 容器配置cors 跨域Filter(Tomcat安装目录/conf/web.xml文件)

备注:此为Tomcat8 以上版本:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
 
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

方式二: SpringBoot Web项目配置添加CORS跨域

方法一、全局cors配置:

 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
 
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

方法二、添加cors配置类

 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

方法三、使用Filter方法,还需要在启动类加上@ServletComponentScan注解

 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@WebFilter(urlPatterns = "*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
        httpResponse.setHeader("Access-Control-Expose-Headers", "*");
        filterChain.doFilter(httpRequest, httpResponse);
    }
 
    @Override
    public void destroy() {
 
    }
}

方式三、nginx配置cors 跨越

server {
	listen       8090;
	server_name  127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

	location / {
			root   E:/nginx-1.15.0/ssm;
			index  index.html index.htm;
			try_files $uri $uri/ /index.html;
        }

	location ~/ssm{
			#Proxy Settings 跨域配置
			add_header Access-Control-Allow-Origin $http_origin;
			add_header Access-Control-Allow-Headers *;
			add_header Access-Control-Allow-Methods *;

			proxy_redirect     off;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
			proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
			proxy_max_temp_file_size 0;
			proxy_connect_timeout      90;
			proxy_send_timeout         90;
			proxy_read_timeout         90;
			
			proxy_pass http://127.0.0.1:8700;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

通过上述配置cors 配置方式,就可以解决Web 项目的跨域问题。

Web 跨域问题实战:

前提描述:公司的最新项目采用微服务(SpringBoot) + Vue(前端框架) + Cas5 单点服务器进行项目的架构和研发,在实际情况部署时,发生相关的跨越问题。重点在于:springboot 微服务项目调用cas5 rest 的协议发生跨域问题。

解决问题过程:

第一步:cas5 服务端的容器Tomcat 配置cors 跨域Filter ,且微服务SpringBoot 项目也配置cors 跨域的配置类

但是,微服务项目调用cas 5 单点服务器rest 协议生成Ticket凭证时(tgt),还是提示存在跨域问题的产生,

第二步:为nginx 代理的springboot 微服务项目和cas 5 单点项目配置cors 跨域配置

server {
	listen       8090;
	server_name  127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

	location / {
			root   E:/nginx-1.15.0/ssm;
			index  index.html index.htm;
			try_files $uri $uri/ /index.html;
        }

	location ~/gcxt {
			#Proxy Settings 跨域配置
			add_header Access-Control-Allow-Origin *;
			add_header Access-Control-Allow-Headers *;
			add_header Access-Control-Allow-Methods *;

			proxy_redirect     off;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
			proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
			proxy_max_temp_file_size 0;
			proxy_connect_timeout      90;
			proxy_send_timeout         90;
			proxy_read_timeout         90;
			
			proxy_pass http://127.0.0.1:8715;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
	
server {
	listen       8098;
	server_name  127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;



	location ~/cas {
			#Proxy Settings 跨域配置
			add_header Access-Control-Allow-Origin *;
			add_header Access-Control-Allow-Headers *;
			add_header Access-Control-Allow-Methods *;


			proxy_redirect     off;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
			proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
			proxy_max_temp_file_size 0;
			proxy_connect_timeout      90;
			proxy_send_timeout         90;
			proxy_read_timeout         90;
			
			proxy_pass http://127.0.0.1:8714;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

但是还是提示错误信息

Access to XMLHttpRequest at 'http://192.168.1.173:8098/cas/v1/tickets' from origin 'http://192.168.1.173:8090' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://192.168.1.173:8090, *', but only one is allowed.

上述的错误信息描述了:允许访问的地址有多个,但只能允许一个用户登入。

我调整后的ngixn 相关代理项目的配置:

server {
	listen       8090;
	server_name  127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

	location / {
			root   E:/nginx-1.15.0/gcxt;
			index  index.html index.htm;
			try_files $uri $uri/ /index.html;
        }

	location ~/gcxt {
			#Proxy Settings 跨越配置
			add_header Access-Control-Allow-Origin $http_origin;
			add_header Access-Control-Allow-Headers *;
			add_header Access-Control-Allow-Methods *;

			proxy_redirect     off;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
			proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
			proxy_max_temp_file_size 0;
			proxy_connect_timeout      90;
			proxy_send_timeout         90;
			proxy_read_timeout         90;
			
			proxy_pass http://127.0.0.1:8715;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
	
server {
	listen       8098;
	server_name  127.0.0.1 localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;



	location ~/cas {
			#Proxy Settings 移除跨域配置


			proxy_redirect     off;
			proxy_set_header   Host             $host;
			proxy_set_header   X-Real-IP        $remote_addr;
			proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
			proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
			proxy_max_temp_file_size 0;
			proxy_connect_timeout      90;
			proxy_send_timeout         90;
			proxy_read_timeout         90;
			
			proxy_pass http://127.0.0.1:8714;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

梳理:ssm 项目配置nginx 代理的cors 跨域配置,cas 项目移除nginx 代理的cors 跨域配置,转而采用tomcat 配置的cors 跨域配置

发布了1266 篇原创文章 · 获赞 275 · 访问量 290万+

猜你喜欢

转载自blog.csdn.net/zhouzhiwengang/article/details/105126443