关于springboot2.4跨域配置问题

2022-07-22,

 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;
    }
}

到此这篇关于springboot2.4跨域配置的文章就介绍到这了,更多相关springboot跨域配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《关于springboot2.4跨域配置问题.doc》

下载本文的Word格式文档,以方便收藏与打印。