SpringBoot 配置跨域问题处理

18 篇文章 0 订阅
13 篇文章 0 订阅

          目前我只用一种方法,跨域专门用跨域过滤处理 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可以方法

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot处理跨域问题可以通过以下步骤进行: 1. 添加跨域配置类:创建一个类并注解为`@Configuration`,并实现`WebMvcConfigurer`接口。在该类中重写`addCorsMappings`方法。 ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许跨域访问的路径 .allowedOrigins("*") // 允许跨域访问的源 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许请求方法 .allowCredentials(true) // 是否发送cookie .maxAge(3600); // 预检间隔时间 } } ``` 2. 注册跨域配置类:在`Application`类上添加注解`@EnableWebMvc`,并将跨域配置类添加到Spring Boot应用中。 ```java @SpringBootApplication @EnableWebMvc public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 配置全局跨域过滤器(可选):如果上述方法无法解决跨域问题,可以使用全局跨域过滤器。 ```java @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept"); response.setHeader("Access-Control-Max-Age", "3600"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } // 省略其他方法 } ``` 通过以上步骤,你就可以在Spring Boot中成功处理跨域问题了。请注意,跨域配置应该根据你的实际需求进行调整,例如允许的源、方法和头部等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值