spring 2.7.14 cors 设置 allowedOrigins(“*“)通配符 失效怎么解决

失效代码:

package com.yukuanyan.searcher_web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

失效原因:

allowCredentials(true)被设置成了ture,说明浏览器应该在请求时携带凭证(credential),如果使用*作为通配符会导致安全问题,所以会导致通配符
allowedOrigins("*")
失效

 解决方法:
将allowCredentials()设置为false

package com.yukuanyan.searcher_web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                // allowOrigins 使用通配符时需要设置为false
                .allowCredentials(false)
                .maxAge(3600);
    }
}

你可能感兴趣的:(spring,java,后端)