Swagger (springdoc) 와 Spring Cloud Gateway 통합

sun1·2023년 9월 7일
0

CS

목록 보기
3/17

📢 MSA 사용시 각 서비스 마다 swagger 주소가 다르므로 이를 통합해야 하고 API Gateway를 통과하여야 한다. ( 즉, 인증 인가 절차를 통과해야 한다 )

마이크로서비스가 API 게이트웨이와 연결되어 있고 게이트웨이만 배포 환경에서 공용 IP 주소로 노출되도록 허용된 경우 API 게이트웨이 URL을 사용하여 Swagger UI를 로드해야 한다.

✅ 각 마이크로 서비스를 API(Application Programming Interface) Gateway 에서 route 해주고 각 서비스에서는 open api url주소를 API Gateway 포트 주소 값으로 이용한다.
이때, 각 마이크로 서비스 스웨거 관련 주소는 서비스 명을 추가해주고 상대 주소값으로 API Gateway 에서 불러준다.

이를 Spring Cloud 와 springdoc를 사용하여 구현하였다.

💡 구현 코드

API Gateway

  • build.gradle
implementation 'org.springdoc:springdoc-openapi-webflux-core:1.5.13'
implementation 'org.springdoc:springdoc-openapi-webflux-ui:1.5.13'
  • application.yml
spring:
  application:
    name: apigateway
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins:
              - 'http://localhost:3000'
              - 'https://localhost:3000'
            allow-credentials: true
            allowedHeaders:
              - x-requested-with
              - Authorization
              - content-type
              - credential
              - X-AUTH-TOKEN
              - X-CSRF-TOKEN  # 허용할 요청 헤더를 설정합니다.
            exposedHeaders:
              - x-requested-with
              - Authorization
              - content-type
              - credential
              - X-AUTH-TOKEN
              - X-CSRF-TOKEN
            allowedMethods:
              - PUT
              - GET
              - POST
              - DELETE
              - OPTIONS
      routes:
        - id: member
          uri: lb://MEMBER
          predicates:
            - Path=/member/update/**, /member/logout, /member/info, /member/delete
            - Method=GET,POST,PUT,DELETE
          filters:
            - AuthenticationHeaderFilter
        - id: member
          uri: lb://MEMBER
          predicates:
            - Path=/member/**
        - id: member-service
          uri: lb://MEMBER
          predicates:
            - Path=/member-service/**


springdoc:
  enable-native-support: true
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true
    path: /swagger-ui.html
    config-url: /v3/api-docs/swagger-config
    urls:
#      - url: /v3/api-docs
#        name: API Gateway Service
#        primaryName: API Gateway Service
      - url: /member-service/v3/api-docs
        name: Member

Member 서비스

  • application.yml
springdoc:
  api-docs:
    path: /member-service/v3/api-docs
  swagger-ui:
    path: /member-service/swagger-ui.html

openapi:
  service:
  	# API Gateway 포트
    url: http://localhost:8000
  • swaggerconfig
@OpenAPIDefinition
@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI(@Value("${openapi.service.url}") String url) {
        return new OpenAPI()
                .servers(List.of(new Server().url(url)))
                .components(new Components().addSecuritySchemes("Bearer",
                        new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")))
                .addSecurityItem(new SecurityRequirement().addList("Bearer"))
                .info(new Info().title("✩ 특화 프로젝트")
                        .description("유저 관련 API")
                        .version("v0.0.1"));
    }

}

🤔 Springfox를 쓴다면?

implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0'
implementation 'io.swagger.core.v3:swagger-annotations-jakarta:2.2.11'

아래는 궁금해서 찾아본 여러가지 내용이다.

[ Gradle 버전 OpenAPI Generator를 이용한 Swagger API 문서 자동생성 ]

[ MSA 환경에서 API 문서 통합 관리 ( Spring restDocs와 Swagger UI 조합) ]

[ Microservices API Documentation with Springdoc OpenAPI ]

0개의 댓글