SpringBoot 配置跨域问题处理

          目前我只用一种方法,跨域专门用跨域过滤处理 CorsFilter 然后通过bean注入交给spring容器一并处理该过程,我们只负责进行配置即可。在这我需要讲解一下AllowCredentials 和AllowedOrigins 匹配使用 ,AllowCredentials 含义就允许携带的认证值进行访问,如果AllowedOrigins为* 全部的话,AllowCredentials 必须为false 否则无效, AllowedOrigins 指定某一些地址,AllowCredentials 则为true,

代码如下:

import org.springframework.boot.context.properties.ConfigurationProperties;
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;

import java.util.List;



@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsFilterConfig {
    /**
     * 源
     */
    protected List<String> originUrl;
    /**
     * 跨域开关
     */
    private String enable;

    public void setEnable(String enable) {
        this.enable = enable;
    }

    public void setOriginUrl(List<String> originUrl) {
        this.originUrl = originUrl;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        if ("true".equals(enable)){
            /*是否允许请求带有验证信息*/
            configuration.setAllowCredentials(true);
            /*允许访问的客户端域名*/
            configuration.setAllowedOrigins(originUrl);
        }else{
            /*是否允许请求带有验证信息*/
            configuration.setAllowCredentials(false);
            /*允许访问的客户端域名*/
            configuration.addAllowedOrigin("*");
        }
        /*允许服务端访问的客户端请求头*/
        configuration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        configuration.addAllowedMethod("*");
        configuration.setMaxAge(3600L);
        configurationSource.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(configurationSource);
    }
}

我这中做法是方便加白名单,生产环境时我们将这个开关打开,然后配置开放对应的ip:如配置文件:

#跨域配置
cors:
  enable: false
  originUrl:
    - http://192.168.18.165
    - http://192.168.18.178:8082
    - http://www.greenet.cn
    - http://192.168.50.140:815
    - http://192.168.50.140:820
    - http://192.168.18.178:8081
    - http://192.168.6.164:5500

想要对哪个ip进行开放的话就加上,然后enable 改为true,如果enable为false的话就是不受跨域限制允许所有的IP可以方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值