春季启动安全发布请求不适用于cors



我使用的是spring-boot框架,我实现了两个rest端点类型get和类型post请求。如果我们从同一来源访问这些端,那么获取和发布请求就可以正常工作。当我试图从react应用程序访问这些端点时,Get请求工作正常,但当我到达第二个端点(请求后(时,获得状态代码401。我在浏览器控制台中找不到任何cors错误
前端代码。

const _HEADERS = {
    'Content-Type': 'application/json',
    'x-xsrf-token': getCSRFToken(),
    'Authorization': 'Basic ' + btoa("admin" + ":" + "admin")
}
let fetchData = async  (resource:string, method:string, postData:Object, mode:string = _SAME_ORGIN, formData:any = null, headers:any = _HEADERS ) => {
    let initObj = {};
    if( method === "GET" ) {
        initObj = {
            method: method,
            mode: mode,
            cache: 'no-cache',
            headers: headers
          };
    } else {
        initObj = {
            method: method,
            mode: mode,
            cache: 'no-cache',
            headers: headers,
            body: formData === null? JSON.stringify(postData): formData
        };
    }
    
    return await fetch( new Request(resource, initObj) );
}

后端代码

Global cors
@Bean
    public WebMvcConfigurer configure() {
        return new WebMvcConfigurer() {
            @Override
            public void  addCorsMappings(CorsRegistry registry) {
                Boolean corsEnabled = Boolean.parseBoolean( environment.getProperty("application.cors.enabled"));
                if( corsEnabled != null && corsEnabled == true ) {
                    registry.addMapping("/**").allowedOrigins("http://localhost:8000");
                }
            }
        };
    }
Security
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 
        .and().authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin();
        http.httpBasic();
        if (corsEnabled != null && corsEnabled == true) {
            http.cors();
        }

更新安全性。

http.csrf().disable().authorizeRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin();
        http.httpBasic();
        if (corsEnabled != null && corsEnabled == true) {
            http.cors();
        }

最新更新