继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

springboot2.4跨域配置

幕布斯7119047
关注TA
已关注
手记 432
粉丝 28
获赞 99

1、如果只是一个简单的springboot demo,用以下配置就行
新建config类import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**

  • @author yk
  • @date 2021/7/19 14:36
    /
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedOriginPatterns("
    ")
    .allowedMethods("*")
    .maxAge(3600)
    .allowCredentials(true);
    }
    }2、但是实际开发中我们需要结合,spring-security、oauth2等等,就会发现上面的配置失效了,那是因为前面的Filter优先级太高了,那我们可以采取如下配置import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.Ordered;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;

/**

  • @author yk

  • @date 2021/7/19 16:21
    */
    @Configuration
    public class CrosConfig {

    @Bean
    public FilterRegistrationBean corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOriginPattern("");
    config.addAllowedHeader("
    ");
    config.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    //这里设置优先级最高
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
    }
    }版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
    本文链接:https://blog.csdn.net/qq_38416500/article/details/118905401

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP