cors 랑 전쟁
package com.example.fanmon_be.global.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsMvcConfig implements WebMvcConfigurer {
@Value("${spring.web.cors.allowed-origins}")
private String allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
corsRegistry.addMapping("/**")
.allowedOrigins(allowedOrigins.split(",")) // ,로 구분된 다수의 도메인 지원
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
}
기존 CorsMvcConfig 파일
다 날리고
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**",config);
return new CorsFilter(source);
}
}
이렇게 쓰고
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()
.anyRequest().authenticated()
)
.addFilter(corsMvcConfig.corsFilter())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(exceptionHandling -> {
exceptionHandling.authenticationEntryPoint(authenticationEntryPoint);
exceptionHandling.accessDeniedHandler(accessDeniedHandler);
});
return http.build();
security config 에 추가
그래도 여전히 cors 오류가 난다....
https://www.qordpsem.store/board/artistboard/70d7f41e-86e4-11ef-b4db-0a2a78c30fc9
https://www.fanmon.site/user/login
현재 상황)
백엔드, 프론트 다 배포 완료
백엔드, 프론트 다 주소 https 로 변경 완료
cors 오류는 사라지고 mixed 오류로 변경됨
지금까지 상황이
1. 백엔드 배포
2. 프론트 배포
cors 오류,,
3. 프론트 https 로 변경
서버 다운은 안되게 개선됐지만 (소켓 cors 에러가 사라져서), 여전히 cors 오류
4. 백엔드 https 로 변경
cors 대신 mixed content 오류
오류 메세지를 보면 request 가 https + 내가 설정한 서브도메인 주소가 아니고 http + ip 주소 이다
가설1) 프론트 코드 중에 http.ip주소 인게 있다?
>> 확인 결과 없음
가설2) 자동배포 시 환경변수로 github secret 에 백엔드 주소를 넣어놨는데 그게 설정이 잘못 되어서?
내용 추가)
aws 비용이 점차 부담되기 시작해서
잠시 ec2 인스턴스들 중지 시키고, s3 파일도 비워줌
다시 재개하려하는데
Main 브랜치에 푸쉬할게 없게 없어서 수동 배포함
어???
git secret 문제 (가설2) 는 아니었던걸로
다시 재개하면서 수동 배포하는 과정에서
.env 에 local 테스트도 해보고 도메인주소로 테스트도 해보다가 오타가 났는데 그게 반영됐다
(www 가 아니라 wwww 라고 오타 ,,)
그래서
s3 버킷을 비우고 다시 수동배포 하려는데
다 비워줬는데
여전히
프론트 배포 도메인으로 접속이되고
오류문구로 wwww.도메인주소 라서 이름이 잘못됐다고 뜬다???
아 그래서 그동안??!
이 블로그를 참고해서 캐시 무효화 바로 될 수 있게 설정해줌
됐다!!
다시 s3에 빌드 파일을 넣어줬다
이제 http + ip 주소가 아니라
https + 도메인 주소에서 받아온다 ㅜ
한 걸음 나아가긴 했지만 여전히 오류,,
소켓은 그대로 200 OK (프론트 주소에서 받아오는 결과)
이런걸 보면 여전히 백을 받아오는게 안되고 있는 것 같다
결국 다른사람들이 말하는것 처럼 cors 는 서버쪽 오류? 백엔드 코드를 고쳐야하는걸까
그 뒤로 계속 여러번 CorsConfig 코드를 고치고 main 에 푸쉬해서 배포 잘되는지 확인하기를 몇날 며칠,,,
블로그를 다 뒤져봐도 그코드가 그 코드였는데
한 블로그에서 찾은 말
"SPRING 3 부터는 CORS 코드 문법이 다르다"
@Configuration
public class CorsMvcConfig {
@Value("${spring.web.cors.allowed-origins}")
private String allowedOrigins;
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(Arrays.asList(allowedOrigins.split(",")));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
해당 글에서 말하는 대로 문법을 바꾸어줬다 (원 출처는 stackoverflow.com)
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsMvcConfig.corsConfigurationSource()))
...
...
...
}
....
}
이건 SecurityConfig 코드,,
이렇게 했는데!!!
진짜 이제 되나 했는데!!!!
여전히 같은 오류가 나서
주변에 다른 사람들한테 수소문했더니 코드 오류가 없는것 같으면
백엔드 빌드 다시해보고
프론트도 캐시 무효화 해주고 다시 빌드해보라고해서
이 과정을 다시 해줬더니
진짜 된다!!!!!
배포된 곳에서
회원 조회 및 수정을 해보았다,,,, 다 잘된다!!
몇날며칠만에 본 저 초록불들이 소중하게 느껴진다 ,,,
배포 정말정말 끝,,,cors 다시는 만나지말자