본문 바로가기
프로젝트/IAteIt

[IAteIt] Swagger Springdoc-openapi3 커스텀 Header 추가하기

by 지금갑시다 2024. 2. 8.

 

 

openapi3 를 사용하기 이전의 Swagger 적용방법에는 Docket 클래스에 Header 값을 추가해주는 방법으로 구현이 가능한 것 같았다.

 

그러나 openapi3를 사용하는 방식에서는 그것과는 조금 달라 글을 작성한다!

 

 

 

1. 프로젝트에 Swagger의 의존성을 추가해준다 (gradle 사용)

dependencies {
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
}

 

 

2. 먼저 Springboot가 Swagger를 인식할 수 있도록 Configuration과 함께 빈을 만들어 준다

@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .addServersItem(new Server().url("/"))
                .info(getInfo())
    }

    public Info getInfo() {
        Info info = new Info();
        info.setTitle("IAteIt");
        info.setDescription("IAteIt API를 알아보자!");
        return info;
    }

}

 

 

이렇게 구성하고 

{baseURL or localhost}/swagger-ui.html 로 접속을 한다면

정상적으로 Swagger가 동작되는 것을 확인할 수 있다!

 

 

참고 URL: 

https://github.com/swagger-api/swagger-codegen/blob/d1dc253c62af8d6e4b8f5531137b2e5af680dce4/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/homeController.mustache#L12

 

 

상단 URL에서 Swagger의 기본 URL설정이 어떻게 구성되었는지 더 확인가능!!

 

 

자 이제 우리의 서비스는 JWT로 사용자 인증을 하기에, HTTP의 헤더에 토큰이 들어가 있어야 한다!

따라서~ 헤더 자리를 만들어 주자!

 

 

이는 OpenAPI의 security 프로퍼티로 넣어주면 된다!

헤더명은 "Authorization"으로 SecurityRequirement 리스트에 추가해주면 된다.

@Configuration 위에 @SecurityScheme을 추가함으로써 헤더에 대한 설정 ui 칸을 만들어준다고 생각하면 된다.

@SecurityScheme(
        type = SecuritySchemeType.APIKEY,
        name = "Authorization",
        description = "access Token을 입력해주세요.",
        in = SecuritySchemeIn.HEADER)
@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .addServersItem(new Server().url("/"))
                .info(getInfo())
                .security(getSecurityRequirement());
    }

    private List<SecurityRequirement> getSecurityRequirement() {
        List<SecurityRequirement> requirements = new ArrayList<>();
        requirements.add(new SecurityRequirement().addList("Authorization"));
        return requirements;
    }

    public Info getInfo() {
        Info info = new Info();
        info.setTitle("IAteIt");
        info.setDescription("IAteIt API를 알아보자!");
        return info;
    }

}

 

 

 

이제 다시 실행해보면~~?

Authorization 버튼이 생성되고, 버튼을 누르고 Value 칸에 테스트 해보고 싶은 토큰을 넣는다

 

 

 

 

api 하나를 실행해보면~

아래와 같이 curl에 헤더에 내가 입력한 value가 포함되어 요청이 가는 것을 확인할 수 있다!

 

 

끘~~

 

 

이렇게 구축한 Swagger는 IAteIt에서 사용되고 있답니다!

 

https://apps.apple.com/kr/app/i-ate-it/id6456377313

 

‎I ate it.

‎Share what you eat in a day 하루동안 먹은 것을 사진으로 공유하는 앱, I ate it. Easily share and connect with others about what you’ve eaten today. When you're pondering what to eat, take a peek at others’ delicious food photos for s

apps.apple.com