코딩 에러 및 질문

응답 헤더 없는 CORS 오류 with Spring Security

요가하는 개발자 2023. 9. 17. 22:38

🌳 에러 코드


응답 헤더 (Authorization’, ‘Authorization-refresh) 토큰 관련 헤더가 들어오지 않는 문제.

 

 

 

 

 

🌳 해결 방법


🌾 해결 방법 : 응답 헤더 설정은 setExposedHeaders 메소드로 해결! 

 

 

 

 

 

 

Before
Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .cors() // cors 설정
            .and()
		...

    return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("<http://localhost:8080>", "..."));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Authorization-refresh", "Cache-Control", "Content-Type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

 

 

 

 

 

 

 

After
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .cors() // cors 설정
            .and()
		...

    return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("<http://localhost:8080>", "..."));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Authorization-refresh", "Cache-Control", "Content-Type"));
    
		/* 응답 헤더 설정 추가*/
		configuration.setExposedHeaders(Arrays.asList("Authorization", "Authorization-refresh"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}