본문 바로가기
Java & Kotlin/Spring

[springdoc-openapi] 고정 header 설정하기

by devson 2022. 12. 31.

서버 API 문서화 시 주로 간편한 설정과 직접 요청을 보낼 수 있는 UI를 제공하는 Swagger UI를 주로 사용한다.

하지만 실서비스 용 서버는 주로 인증 기능이 붙어있기 때문에 API 요청 시 인증 용 토큰 등이 필요한 경우가 대다수이다.

 

이번 포스팅에서는 springdoc-openapi를 사용하여 Swagger UI를 구성할 때,

header 기반 인증을 처리하는 방법 중 하나로 고정 header를 설정하는 방법에 대해 알아보겠다.

(org.springdoc:springdoc-openapi-ui:1.6.14 기준)

 

(코드 예제는 여기에서 확인할 수 있다)


※ 참고

Springfox는 현재 maintain이 되고있지 않기 때문에, 되도록 springdoc-openapi를 사용하는 것을 추천한다.


 

아래와 같이 X-AUTH-TOKEN header를 통해 인증 과정을 거치는 API가 있다고 하자.

(※ 참고: RFC 문서 상 "X-" header 는 deprecated 되어있으니 custom header에 대해 다른 네이밍을 쓰는 것을 고려해도 좋을 것이다)

import io.swagger.v3.oas.annotations.Parameter
import mu.KotlinLogging
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RestController
@RestController
class AuthController {
private val logger = KotlinLogging.logger { }
@GetMapping("/auth")
fun authenticatedRequest(
@Parameter(hidden = true) @RequestHeader("X-AUTH-TOKEN", required = false) authToken: String?
): String {
this.logger.info { "auth token is `${authToken}`" }
if (authToken == null) {
return "not allowed"
}
return "authenticated!"
}
}

 

openapi 설정은 아래와 같이 하도록 하자.

import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType
import io.swagger.v3.oas.annotations.security.SecurityScheme
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.security.SecurityRequirement
import org.springdoc.core.GroupedOpenApi
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
private const val AUTH_TOKEN_HEADER = "X-AUTH-TOKEN"
// add `Authorize` button - https://www.baeldung.com/spring-openapi-global-securityscheme#springdoc-openapi-base-configuration
@SecurityScheme(
type = SecuritySchemeType.APIKEY, `in` = SecuritySchemeIn.HEADER,
name = AUTH_TOKEN_HEADER, description = "Auth Token",
)
@Configuration
class OpenApiConfiguration {
@Bean
fun api(): GroupedOpenApi {
return GroupedOpenApi.builder()
.group("api")
.addOpenApiCustomiser {
it
.info(
Info()
.title("API")
.description("API Document")
.version("1.0")
)
// enable to send header - https://github.com/swagger-api/swagger-ui/issues/5715#issuecomment-624866240
.security(
listOf(
SecurityRequirement().addList(AUTH_TOKEN_HEADER),
)
)
}
.pathsToMatch("/**")
.build()
}
}
  • 13~16: @SecurityScheme 설정을 통해 Swagger UIAuthorize 버튼을 추가한다.
  • 33~37: security 설정을 통해 요청 header에 값을 담아 보내도록 설정한다.

(두 개의 설정을 따로 해줘야해서 조금 번거롭긴 하지만 하나의 설정으로 처리하는 방법을 찾질 못했다)

 

 

http://localhost:8080/swagger-ui/index.html 에 접속하여 Swagger UI를 확인하면 아래와 같이 Authorize 버튼을 확인할 수 있고,
이를 통해 인증 header인 X-AUTH-TOKEN 값을 고정시킬 수 있다.

 

 

위와 같이 인증 header를 설정을 한 후, 인증이 필요한 API에 요청을 보내면 인증 처리가 잘 된것을 확인할 수 있다.

 

 


참고

 

댓글