spring boot 프로젝트에서 JWT 를 통한 인증을 수행하는데 Swagger 문서에는 인증에 대한 description 이 없어 그 부분을 추가하려고 한다. 사용하고 있는 라이브러리는 아래와 같다.
// Swagger 설정
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
Swagger 전역 설정
모든 API 에 대한 인증 설정을 추가하려면 전역 설정을 할 수 있다. 그렇다고 진짜로 인증을 요구하는 것은 아니다.
만약에 JWT 인증이 필요없는 API 가 있다면 그 API 에 대해서도 인증은 활성화되어있지만 JWT에 대한 검증 로직이 없기 떄문에 정상적으로 요청이 가능하다.
공식 문서를 통해 JWT 인증을 요구하는 설정 방법에 대해 알아보자.
OpenAPI 3.0에서 Bearer 인증은 type: http와 scheme: bearer를 가진 보안 스키마로서 설명된다.
1. components/securitySchemes 아래에서 보안 스키마 정의
2. 전체 API에 글로벌하게 적용하거나 특정 작업에만 적용하기 위해서 security 키워드 사용
openapi: 3.0.0
...
# 1) Define the security scheme type (HTTP bearer)
components:
securitySchemes:
bearerAuth: # arbitrary name for the security scheme
type: http
scheme: bearer
bearerFormat: JWT # optional, arbitrary value for documentation purposes
# 2) Apply the security globally to all operations
security:
- bearerAuth: [] # use the same name as above
openapi 의존성이 추가되었다는 가정하에 SwaggerConfig 를 만들어 전역 설정을 해보자.
package com.limnj.til.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.addSecurityItem(new SecurityRequirement().addList("bearerAuth")) // 전역 설정
.components(new Components()
.addSecuritySchemes("bearerAuth", new SecurityScheme() // 스키마 정의
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
- 실행 결과
swagger url 에 접속하면 자물쇠가 각 API 마다 생성되었음을 확인할 수 있다.

자물쇠를 누르면 아래와 같이 JWT 를 입력할 수 있는 팝업을 확인할 수 있다.

Swagger 부분 설정
전역으로 편리하게 설정할 수도 있지만 사실 어떤 API 가 진짜 인증이 필요한 지에 대한 구분이 굉장히 불편하다.
따로 문서를 만들어 관리해야 하는 등의 노력을 줄이기 위해 부분 설정을 해보자.
SwaggerConfig 에서는 전역 설정을 했던 부분에서 .addSecurityItem() 을 제거한다.
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
// .addSecurityItem(new SecurityRequirement().addList("bearerAuth")) // 제거
.components(new Components()
.addSecuritySchemes("bearerAuth", new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
그 이후 Controller 단에서 인증이 필요한 API 에 아래와 같은 어노테이션을 추가한다.
@PostMapping("/shorten")
@Operation(security = { @SecurityRequirement(name = "bearerAuth") }) // ★추가
public ResponseEntity<String> shortenUrl(@RequestBody String originalName){
..
return ResponseEntity.ok("");
}
- 실행결과
Swagger ui 로 접속해보았을 때 아래와 같이 특정 API 에서만 자물쇠가 활성화 되어있음을 확인할 수 있다.

참고
https://swagger.io/docs/specification/authentication/bearer-authentication/
'Web' 카테고리의 다른 글
| [Spring] actuator 를 통한 shutdown endpoint 생성 (0) | 2023.12.10 |
|---|---|
| [Spring] RestTemplate 과 WebClient (0) | 2023.12.03 |
| [Spring] Spring 3.x + Swagger 설정 (0) | 2023.11.19 |
| [System Design] URL 단축기 설계 -1 (0) | 2023.11.05 |
| [Spring] Transaction 에 대해서 (3) | 2023.10.22 |