Swagger Server 추가 ( Spring Boot 3.x )

송형근·2024년 8월 28일
3

TIL

목록 보기
23/43
post-thumbnail

MSA로 구성된 프로젝트에서 Swagger를 Gateway 통해서 요청할 수 있도록 Swagger 설정에서 Server 목록을 추가

Application.yml

  • dev와 prod에서 각각 다른 host와 port를 적을 수 있도록 Value를 추가해줬음
    • application-dev.yml
      server:
        host: localhost
        gateway:
          port: 19091
  • server.host 를 통해 서버의 호스트를 지정
  • server.gateway.port 를 통해 gateway 서버의 포트를 지정

Swagger Configuration

  • SwaggerConfiguration에서 서버 목록을 추가해줌
    • SwaggerConfig
      @OpenAPIDefinition(
              info = @Info(title = "Service API 명세서",
                      description = "Service API 명세서",
                      version = "v1"))
      @Configuration
      public class SwaggerConfig {
      
          @Value("${server.host}")
          String host;
      
          @Value("${server.port}")
          String serverPort;
      
          @Value("${server.gateway.port}")
          String gatewayPort;
      
          @Bean
          public GroupedOpenApi publicAPI(){
              return GroupedOpenApi.builder()
                      .group("com.blue.service")
                      .pathsToMatch("/**")
                      .build();
          }
      
          @Bean
          public OpenAPI customOpenAPI() {
              List<Server> serverList = new ArrayList<>();
              Server server = new Server()
                      .url("http://"+host+":"+serverPort+"/api")
                      .description("Server");
              Server gatewayServer = new Server()
                      .url("http://"+host+":"+gatewayPort+"/api")
                      .description("Gateway Server");
              serverList.add(gatewayServer);
              serverList.add(server);
              return new OpenAPI()
                      .servers(serverList)
                      .components(new Components()
                              .addSecuritySchemes("JWT-Token", new SecurityScheme()
                                      .type(SecurityScheme.Type.HTTP)
                                      .scheme("bearer")
                                      .bearerFormat("JWT")
                                      .in(SecurityScheme.In.HEADER)
                                      .name("Authorization")))
                      .addSecurityItem(new SecurityRequirement().addList("JWT-Token"));
          }
      }
  • ServerList를 생성하고, API Server와 Gateway Server의 정보를 List에 추가
  • OpenAPI().servers(serverList)를 통해 서버 목록을 추가함

CorsConfigurer

  • Cors 설정이 안되어있어 Gateway Server를 사용해서 API 요청했을 때 CORS 에러가 발생
  • WebMvcConfigurer를 활용해 Cors설정을 추가
    • WebCorsConfigurer
      @Configuration
      public class WebCorsConfigurer implements WebMvcConfigurer {
      
          @Value("${server.host}")
          String host;
      
          @Value("${server.port}")
          String serverPort;
      
          @Value("${server.gateway.port}")
          String gatewayPort;
      
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**")
                      .allowedOrigins("http://" + host + ":" + serverPort,"http://" + host + ":" + gatewayPort)
                      .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                      .allowedHeaders("*");
          }
      
      }

Gateway Server Cors 설정

  • 위의 설정까지 잘 마치면 Gateway Server의 Swagger에 접속해서 API요청을 할 경우 문제가 없지만, API Server의 Swagger에 접속해서 Gateway Server로 요청을 보낼경우 CORS 에러가 발생함
  • Gateway Server의 cloud gatway설정에서 아래의 Cors 설정을 추가
    • application.yaml
      spring:
        cloud:
          gateway:
            default-filters:
              - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials
            globalcors:
              cors-configurations:
                '[/**]':
                  allow-credentials: true
                  allowedHeaders:
                    - x-requested-with
                    - Authorization
                    - content-type
                    - credential
                    - X-AUTH-TOKEN
                    - X-CSRF-TOKEN
                    - X-User-Name
                  exposedHeaders:
                    - x-requested-with
                    - Authorization
                    - content-type
                    - credential
                    - X-AUTH-TOKEN
                    - X-CSRF-TOKEN
                    - X-User-Name
                  allowedMethods:
                    - GET
                    - POST
                    - PUT
                    - PATCH
                    - DELETE
                    - OPTIONS
    • application-dev.yaml
        cloud:
          gateway:
            globalcors:
              cors-configurations:
                '[/**]':
                  allowedOrigins:
                    - 'http://localhost:19092'
  • prod 환경의 경우 추후 환경변수로 Origin 추가 예정
profile
기록을 남겨보자

1개의 댓글

comment-user-thumbnail
2024년 8월 28일

유정감

답글 달기