Spring Gateway网关配置跨域

package com.atguigu.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsFilterConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 注意使用org.springframework.web.cors.reactive包下的
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(source);
    }
}

但是在使用SpringBoot2.6版本时,需要注意:
在将allowCredentials设置为true时,需要将corsConfiguration.addAllowedOrigin("*");替换为corsConfiguration.addAllowedOriginPattern("*");
否则会报错:

posted @ 2022-04-09 23:37  kanaliya  阅读(194)  评论(0)    收藏  举报