SpringBoot + SpringSecurity 프로젝트에 Swagger 3.0 적용하기

반응형
728x90
반응형

이전 버전 Swagger 2.0 적용 방법

https://devfunny.tistory.com/313

 

SpringBoot에 Swagger을 빠르게 적용해보기

Swagger 요즘 백엔드 개발은 ModelAndView 방식보다는 API 위주의 어플리케이션을 권장하고 있다. API 개발이 많아짐에 따라, 프로젝트 안의 API를 관리할 수 있는 문서가 필요해졌다. API 문서를 만들

devfunny.tistory.com

 

 

Swagger 3.0 적용

1) build.gradle

implementation 'io.springfox:springfox-boot-starter:3.0.0'

 

2) SwaggerConfig.java

package com.api.shop.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ComponentScan(basePackages = {
        "com.api.shop.modules.controller"
})
public class SwaggerConfig {

    /** swagger */
    @Bean
    public Docket ShopApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Shop API")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.api.shop.modules.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(this.ShopApiInfo())
                .tags(   new Tag("AuthController", "Auth API")
                       , new Tag("MemberController", "Member API")
                );

    }

    private ApiInfo ShopApiInfo() {
        return new ApiInfoBuilder()
                .title("shop API")
                .description("shop API")
                .termsOfServiceUrl("http://www.shop-api.com")
                .version("1.0")
                .build();
    }
}

 

3) SecurityConfig.java

package com.api.shop.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@RequiredArgsConstructor
@Configuration
@EnableWebSecurity // 시큐리티 활성화 -> 기본 스프링 필터체인에 등록
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String[] PERMIT_URL_ARRAY = {
            /* swagger v2 */
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            /* swagger v3 */
            "/v3/api-docs/**",
            "/swagger-ui/**"
    };

    /**
     * configure
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // swagger API 호출시 403 에러 발생 방지
                .authorizeRequests()
                .antMatchers(PERMIT_URL_ARRAY).permitAll()
                .anyRequest().authenticated();
    }
}

 

4) application.yml

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

 

Swagger 접속

URL : http://localhost:8080/swagger-ui/

 

 

에러 해결 방법

1) Failed to start bean 'documentationPluginsBootstrapper'; NullPointerException 에러 발생

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

 

- application.yml
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

 

2) url 접속시 403 Error

- SecurityConfig.java security 허용 URL 리스트
...
    private static final String[] PERMIT_URL_ARRAY = {
            /* swagger v2 */
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            /* swagger v3 */
            "/v3/api-docs/**",
            "/swagger-ui/**"
    };
...

 

 

3) swagger 접속 후 API response 에 403 Error

- SecurityConfig.java
...
   @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // swagger API 호출시 403 에러 발생 방지
                .authorizeRequests()
                .antMatchers(PERMIT_URL_ARRAY).permitAll()
                .anyRequest().authenticated();
    }
...

 

 

반응형

Designed by JB FACTORY