[백업][가리사니] 클라우드 플레어로 백엔드 프록시 및 프론트 분리.
back-end, cloudflare, front-end

이 문서는 가리사니 개발자 포럼에 올렸던 글의 백업 파일입니다. 오래된 문서가 많아 현재 상황과 맞지 않을 수 있습니다.

이번 편은 백엔드의 분리입니다. 프론트엔드 분리는 https://gs.saro.me/2023/01/31/%EB%B0%B1%EC%97%85-%EA%B0%80%EB%A6%AC%EC%82%AC%EB%8B%88-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%ED%94%8C%EB%A0%88%EC%96%B4-pages-%EC%97%90-%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C-%EC%A7%81%EC%A0%91-%EB%B0%B0%ED%8F%AC%ED%95%98%EA%B8%B0.html 를 참조하시면 됩니다.

서버 구조

설명

아래와 같이 라우팅을 변경해야 합니다.

우선순위 구분 이전 할당 경로 변경 할당 경로
1 백엔드 /api/* api.도메인/api/*
2 프론트 /* test.도메인/*

프론트의 api 주소도 변경해 주었습니다.

VITE_API_PATH=https://api.anissia.net/api
(생략)
const api = import.meta.env.VITE_API_PATH;
(생략)
public getScheduleAnimeList(week: number|string): Promise<Anime[]> {
    return ajax.fetch(`${api}/anime/schedule/${week}`)
        .then(list => list.map((e: any) => Object.assign(new Anime(), e)));
}
public getAnimeCaptionList(animeNo: string|number): Promise<AnimeCaption[]> {
    return ajax.fetch(`${api}/anime/caption/animeNo/${animeNo}`)
        .then(list => list.map((e: any) => Object.assign(new AnimeCaption(), e)));
}
(생략)

서로 다른 도메인에서 통신하기 위해 cors 처리를 해줍시다.

(스프링 시큐리티 기준.. 각자 가지고 있는 플랫폼에 맞게 처리.)

(생략)
override fun configure(http: HttpSecurity) {
    http.cors().configurationSource(corsConfigurationSource())
}
(생략)
fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration()
    // 스프링 정책상 allowCredentials 을 사용하면 * 를 사용할 수 없다고 한다.
    configuration.allowedOrigins = listOf("https://anissia.net", "https://test.anissia.net", "https://api.anissia.net")
    // 다행히 메서드와 해더는 *가 가능하다.
    // 보안은 중시한다면 원하는 동작 외에 닫아도 되지만.
    // 자바-서블릿 기준으로 한 10년도 더 전부터 GET, POST, OPTIONS를 제외하면 실제와 다르게 작동하여 특별한 위험이 없다. (그렇기 때문에 REST API가 가능하다)
    configuration.allowedMethods = listOf("*")
    configuration.allowedHeaders = listOf("*")
    // 세션을 위해 필수이다.
    configuration.allowCredentials = true
    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)
    return source
}

allowCredentials=true, allowedOrigins=* 으로 줄 경우 나는 오류

ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
	at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:473)

설명 정상 동작을 확인 할 수 있습니다.

충분히 테스트에 성공하면 test.도매인 에서 도메인 으로 이동할 예정입니다.