简体   繁体   中英

Spring boot security post request not working with cors

I'm using the spring boot framework, I have implemented two rest endpoints type get and type post requests. Get and post requests are working fine if we access those ends from the same origin. When I'm trying to access those endpoints from react application, the Get request is working fine but when I hit the second endpoint (post request) getting status code 401. I couldn't find any cors error in browser console
Front end code.

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

Backend code

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

Update security.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM