JUnit 테스트 - CORS 관련

jeongjin-kim·2023년 7월 25일

JUnit5

목록 보기
11/11
post-thumbnail

최주호 강사님의 인프런 강좌 정리 및 실습한 기록

postman 에서는 서버에서 전달한 jwt 토큰을 응답헤더에서 바로 확인할 수 있다. 하지만 크롬에서 확인해보면 응답헤더의 토큰을 찾을 수 없다.

이를 위해, CORS 설정하는 곳에서 헤더를 노출시켜야 한다.

public CorsConfigurationSource corsConfigurationSource() {

    CorsConfiguration configuration = new CorsConfiguration();
    configuration.addAllowedHeader("*");            //
    configuration.addAllowedMethod("*");            // GET, POST, PUT, DELETE (Javascript 요청 허용)
    configuration.addAllowedOriginPattern("*");     // 모든 주소 허용 (react ip 만 허용)
    configuration.setAllowCredentials(true);        // 클라이언트에서 쿠키 요청 허용
    configuration.addExposedHeader("Authorization");
    // 모든 주소에 위에서 생성한 config 를 적용시킨다.
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

SecurityFilterChain 에 등록하면 된다. 스프링 시큐리티가 버전이 올라가며 등록하는 방식이 달라졌다.


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

	// ...
    
    http.cors(cors -> 
    	cors.configurationSource(corsConfigurationSource())
   );
   
  	// ...
}

0개의 댓글