예약 도메인 프로젝트에 Swagger를 적용하려고 한다. 프로젝트는 스프링부트 2.7.x -> 3.xx 로 마이그레이션을 진행할 예정이기에 이 글에서 Swagger는 스프링부트 2.7x 버전에 적용되는 글임을 미리 알린다.
Swagger란?
Swagger는 Api 설계 및 문서화를 위한 프레임 워크로 RESTful Api를 직관적이고 체계적으로 관리하는데 유용한 도구이다. Swagger는 주로 개발자가 API의 사용법을 쉽게 이해하고 테스트 할 수 있도록 도와주는 API문서화 도구로 활용되며 Swagger를 통해 API의 구조와 동작을 명확히 정의할 수 있기에 클라이언트 개발자와 서버 개발자간의 소통 문서로도 활용할 수 있을것 같다.
장점
자동화 : API 코드만 작성하면 Swagger가 API문서를 자동으로 생성하므로 별도의 문서 작성이 필요 없다.
시각화 : Swagger UI를 통해 API 구조를 쉽게 시각화 하고 테스트 해 볼 수 있다.
코드 생성 : API문서에서 서버 및 클라이언트 코드를 자동으로 생성할 수 있어 생산성을 높인다.
의존성 설정하기(feat: Spring Boot 2.7.5)
implementation("io.springfox:springfox-boot-starter:3.0.0")
스프링 2.7x버전에서의 의존성 설정이다. springfox는 더이상 활발히 업데이트 되지 않으며 특히 Spring Boot 3.x 이상 버전과 호환 되지 않는다.
Spring Boot 3.x버전에서는 org.springdoc:springdoc-openapi-starter-webmvc-ui 를 사용해야 한다. 이에 대한 글은 마이그레이션을 진행할때 따로 작성 하도록 하겠다.
실행오류 발생 ApplicationContextException
의존성을 설정하고 프로그램을 재실행시키니 오류가 발생했다.
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
찾아보니 Spring Boot 2.6 버전부터는 경로 매칭을 위해 PathPatternParser를 기본적으로 사용한다. 그러나 springfox 는 AntPathMatcher 로 설정을 변경해줘야 한다.
설정파일 추가
mvc:
pathmatch:
matching-strategy: ant_path_matcher
이 설정을 통해 Spring MVC 가 AntPathMatcher를 사용하여 URL 매칭을 처리하게 된다.
Swagger UI 경로
http://localhost:8080/swagger-ui/index.html
Spring Security Swagger 권한 설정
authorizeHttpRequests(authorize -> authorize
.antMatchers("/api/v1/auth/**", "/h2-console/**",
"/swagger-ui/**",
).permitAll()
.anyRequest().authenticated()
)
처음에는 단순히 Swagger uri만 접근 권한 설정을 해주었는데 접속이 되지 않았다.
Swagger는 자체적으로 여러 리소스와 API 앤드포인트를 가지고 있고 이 경로들이 기본적으로는 보안에 걸려있기 때문에 Swagger UI 및 Swagger API 문서에 접근할 수 없게 된다. 그래서 Swagger와 관련된 경로들을 따로 설정 해 주어야 한다.
.authorizeHttpRequests(authorize -> authorize
.antMatchers("/api/v1/auth/**", "/h2-console/**",
"/v2/api-docs", "/v3/api-docs", "/v3/api-docs/**", "/swagger-resources",
"/swagger-resources/**", "/configuration/ui", "/configuration/security", "/swagger-ui/**",
"/webjars/**", "/swagger-ui.html").permitAll()
.anyRequest().authenticated()
)
위의 접근 권한 설정을 마치니 Swagger UI에 잘 접속 할 수 있었다.