반응형

프론트-서버 간의 CORS 문제 해결을 하기위해 Spring Security 설정을 진행했다.


      
@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:3000>", "..."));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "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;
}

여러 블로그들의 Spring Security CORS 설정을 참고하여 위와 같이 설정했다.

위의 코드를 설정하니, CORS 문제는 해결되었지만 로그인 시 응답 헤더에 토큰 관련 헤더가 들어오지 않았다.

headers에 AccessToken, RefreshToken 헤더인

‘Authorization’, ‘Authorization-refresh’가 들어오지 않았다.

 

위의 코드중에 configuration.setAllowedHeaders에 설정을 해줬는데, 왜 안들어오는지 이유를 몰랐었다.

그러던 중에, setExposedHeaders 메소드를 발견했다.

응답 헤더 설정은 setExposedHeaders 메소드를 통해 할 수 있었다.


      
@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:3000>", "..."));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "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;
}

위처럼 응답 헤더 설정을 추가하니, 응답 헤더에 값이 제대로 들어오게 되었다.

 


Refernece

https://kingchan223.tistory.com/m/230

 

react - header의 Authorization받기

프론트에서 fetch로 서버에 로그인 요청을 하면 서버에서 jwt토큰을 만들어 header에 심어 응답을 해주는데, 자꾸 프론트에서 "Authorization"으로 응답을 받지 못해 이것저것 다하다가 많은 시간을 날

kingchan223.tistory.com

 

반응형
BE_성하