[Java] Swagger Security와 Interceptor 예외 경로를 리스트로 통일하여 관리하기

유영석·2024년 12월 24일
0

회원가입, 로그인 등의 API에서 인증(Authorization)이 필요하지 않은 경우, Swagger 자물쇠 표시 제거 설정과 Interceptor 각각에서 처리해야하는 불편함이 있습니다. 이 문제를 해결하기 위해, 예외 처리할 경로를 리스트로 관리하여 직관적이고 편리하게 수정할 수 있는 방법을 소개합니다.

  1. 예외 처리할 경로 정의
    먼저, 인증이 필요하지 않은 경로를 관리할 클래스를 정의합니다. 이 클래스는 예외처리할 경로를 배열로 저장하고, 이를 다른 설정에서 쉽게 사용할 수 있게 해줍니다.
// constant/ExcludedPaths.java

public class ExcludedPaths {
    public static final String[] PATHS = {
            "/auth/sign-up", "/auth/sign-in", // 회원 가입 및 로그인
            "/nice/**", // 회원가입에서 사용될 nice 본인인증
            "/swagger-ui/**", "/v3/api-docs/**" // Swagger 문서
    };
}
  1. WebConfig 파일에서 예외 경로 처리
    이제 WebConfig 파일에서, 예외 처리할 경로를 Interceptor에 추가하여 인증이 필요하지 않은 경로를 처리합니다. 이를 통해 모든 경로를 Interceptor가 처리하면서, 인증이 필요하지 않은 경로는 제외할 수 있습니다.
// config/WebConfig.java

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
    private final AuthInterceptor authInterceptor;

	...

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**")
                // 인증이 필요하지 않은 경우 Interceptor에 추가해 예외처리 해야한다.
                .excludePathPatterns(ExcludedPaths.PATHS);
    }
    
    ...

}
  1. Swagger 설정 및 예외 경로에서 보안 해제
    Swagger에서 경로 패턴 매칭은 자동으로 처리되지 않기 때문에, 경로를 직접 비교하여 보안 자물쇠를 해제해야 합니다. 이를 위해 OpenApiCustomizer를 사용하여 예외 경로에서 보안 항목을 제거합니다.
// config/SpringConfig.java

@Configuration
public class SpringConfig {
    @Bean
    public OpenAPI openAPI() {
        String jwt = "JWT";
        SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwt);
        Components components = new Components().addSecuritySchemes(jwt, new SecurityScheme()
                .name("Authorization")
                .type(SecurityScheme.Type.HTTP)
                .scheme("bearer")
                .in(SecurityScheme.In.HEADER)
                .bearerFormat(jwt)
        );

        return new OpenAPI()
                .components(components)
                .info(new Info().title("Swagger").description("Backend API Swagger UI").version("0.0.1"))
                .addSecurityItem(securityRequirement);
    }

    @Bean
    public OpenApiCustomizer openApiCustomizer() {
        return openApi -> {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            // ExcludedPaths 경로들은 자물쇠를 해제
            for (String pattern : ExcludedPaths.PATHS) {
                // 모든 경로를 확인하여 패턴 매칭
                for (Map.Entry<String, PathItem> entry : openApi.getPaths().entrySet()) {
                    String path = entry.getKey();
                    PathItem pathItem = entry.getValue();

                    // 경로 패턴이 일치하면 자물쇠 해제
                    if (antPathMatcher.match(pattern, path)) {
                        pathItem.readOperations().forEach(operation -> {
                            // 보안 항목을 없애는 방식으로 자물쇠 해제
                            operation.setSecurity(new ArrayList<>());
                        });
                    }
                }
            }
        };
    }
}
  1. 결과
    이 설정을 통해 새로운 API에서 인증이 필요하지 않은 경로가 생기면, ExcludedPaths에 경로만 추가하면 됩니다. Swagger와 Interceptor에서 각각 두 번 작업하는 불편함을 해소할 수 있습니다. 간편하게 예외 경로를 관리하고, 보안 설정을 자동으로 처리할 수 있어 개발이 더욱 편리해집니다.
profile
ENFP FE 개발자 :)

0개의 댓글

관련 채용 정보