springboot+springsecurity跨域配置完整版(俺被坑了一个上午,特此前来用爱发电)

springboot跨域配置不必多说,网上很多:
首先配置好,我用的是继承WebMvcConfigurer配置,还可以通过过滤器配置,我觉得这样应该是最方便了,缺点就是这种配置不能在interceptor中再配置header。

@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //所有请求都允许跨域,使用这种配置方法就不能在 interceptor 中再配置 header 了
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }
}

接着是配置springsecurity:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf() 		//其他代码略,这里只贴出跨域必要的代码
    }

查看源码就能发现.csrf()是通过CorsConfigurationSource去配置的,所以我们要重新注入一个bean,

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "OPTIONS", "DELETE"));
        configuration.setAllowCredentials(true);
        configuration.applyPermitDefaultValues();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

其中把博主倒弄了半天的就是这一行代码:

configuration.setAllowCredentials(true);

如果不加上,跨域请求时会出现错误:
The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’.
博主原本还以为是springboot配置跨域时出的问题,后来认真测试了一番才得出结果,希望对各位有帮助。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值