Spring Boot에서 Swagger UI 커스터마이징과 보안 적용
Spring Boot 환경에서 Swagger UI를 커스터마이징하고 OAuth2·JWT 기반 인증을 연동해 API 접근 제어를 구현하는 방법과 설정, 코드 예제 및 주의사항 설명
목차
개요
API 문서를 개발 환경뿐 아니라 운영 환경에서도 안전하고 보기 좋게 제공하려면 Swagger UI 커스터마이징과 보안 적용이 필수다. 이 글에서는 springdoc을 기준으로 Swagger UI를 꾸미는 방법과 OAuth2/JWT 기반 인증을 연동해 문서 접근 및 API 호출을 보호하는 과정을 단계별로 설명한다. 처음 보는 사람도 이해할 수 있도록 설정 파일과 Java 코드 예제를 함께 제시한다.
필요 라이브러리
springdoc-openapi와 Spring Security의 OAuth2 리소스 서버 모듈을 사용한다. 빌드 툴에 따라 의존성을 추가하면 된다.
Maven 의존성 예제
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwt</artifactId>
<version>3.18.2</version>
</dependency>
Swagger UI 커스터마이징
springdoc은 application properties/yml로 기본 UI를 손쉽게 조정할 수 있다. 더 세밀한 변경은 커스텀 CSS나 커스텀 index.html을 사용한다.
application.yml 예제
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
display-operation-id: false
display-request-duration: true
operations-sorter: alpha
tags-sorter: alpha
doc-expansion: none
oauth2-redirect-url: /swagger-ui/oauth2-redirect.html
config-url: /v3/api-docs/swagger-config
위 설정으로 기본 동작을 제어한다. doc-expansion, operations-sorter 등으로 가독성을 개선할 수 있다.
커스텀 CSS 또는 HTML 적용
더 강한 커스터마이징이 필요하면 resources/static 내에 swagger-ui를 덮어쓴다. 예를 들어 CSS 파일을 적용하려면 static/css 폴더에 파일을 두고 index.html에서 링크한다.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>API 문서</title>
<link rel="stylesheet" href="/css/custom-swagger.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="/swagger-ui-bundle.js"></script>
<script>window.onload = function() { /* 초기화 코드 */ };</script>
</body>
</html>
이때 springdoc의 기본 제공 파일 경로와 충돌하지 않도록 주의한다. index.html을 직접 수정하면 업데이트 시 동작이 달라질 수 있다.
보안 적용 (springdoc swagger 보안 설정)
문서 자체를 공개하지 않거나, UI에서 API 호출 시 인증 토큰을 사용하도록 설정하려면 OpenAPI 스키마에 보안설정을 추가하고, Spring Security로 엔드포인트를 보호해야 한다.
OpenAPI 보안 스키마 정의
스웨거 문서에 인증 방식을 명시하면 UI에서 Authorize 기능을 사용할 수 있다. @SecurityScheme을 사용한 예제는 다음과 같다.
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "JWT"
)
public class OpenApiConfig {
// 빈 클래스 또는 추가 설정
}
이 정의로 각 컨트롤러의 @SecurityRequirement를 통해 보안 적용 상태를 문서화할 수 있다.
Spring Security 설정 (JWT 리소스 서버 예제)
Spring Security의 최신 방식(SecurityFilterChain 빈)을 사용한 예제다. Swagger UI 경로는 열어두고 API는 인증하도록 설정한다.
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt()
);
return http.build();
}
위 설정으로 문서 조회와 UI 로딩은 허용하되, 실제 API 호출에는 JWT 검증을 적용한다.
Swagger UI에서 OAuth 연동 (swagger spring boot oauth)
OAuth2 인증 서버와 연동해 UI 상단의 Authorize 버튼으로 토큰을 발급받아 API를 호출하려면 springdoc 설정을 추가한다.
springdoc:
swagger-ui:
oauth:
client-id: your-client-id
client-secret: your-client-secret
app-name: Swagger UI
realm: your-realm
scope-separator: ' '
additional-query-string-params: {}
use-basic-auth-with-access-code-grant: false
OAuth2에서 Authorization Code나 Implicit Flow를 사용할 수 있다. OIDC를 함께 사용하는 경우 리디렉션 URL을 정확히 맞춰야 한다.
배포 시 주의사항
- 운영 환경에서 문서 공개 여부를 결정한다. 문서를 열어두면 내부 API 정보가 노출될 수 있다.
- static으로 덮어쓴 swagger UI 파일은 배포 파이프라인에서 관리 방식을 통일한다.
- OAuth 클라이언트 비밀값 등 민감 정보는 환경 변수나 시크릿 관리 시스템으로 관리한다.
- CSP(콘텐츠 보안 정책)나 X-Frame 옵션 등 보안 헤더를 점검한다.
요약
springdoc을 이용하면 Swagger UI를 간단히 커스터마이징할 수 있다. application.yml 설정과 커스텀 리소스를 조합해 화면을 꾸미고, OpenAPI 보안 스키마와 Spring Security를 연동해 문서와 API를 보호한다. OAuth2 또는 JWT 연동 예제를 통해 UI에서 인증 후 API를 호출하도록 구성하면 개발자 경험과 보안 모두 향상된다.