본문 바로가기
  • 2025
인턴일기(티디아이)

[사이드] swagger 적용 삽질 기록

by soonrang 2024. 7. 25.

 

 

요즘 내 인생을 요약하자면

 

 

그래 빡친 햄스터다

요즘 햄스터가 입에 달라붙어서 뭐만하면 햄스터라고 하는데

누군가는 귀여운척 한다고 느낄 수 있겠다. (어쩔)

 

그냥 만만이 룰 > 햄스터 > 호랑이가 되고 싶은 햄스터

 

여튼 이런 말을 적을 시간이 없다 빨리 다시 코드 짜러 가야하니까

우선 핵심적인 오류코드는 다음 링크에 있는 문제와 유사했다.

https://stackoverflow.com/questions/61729822/strict-mime-type-checking-is-enabled-refused-to-execute-script-from-url-its

 

strict mime type checking is enabled, refused to execute script from '<url>' its mime type ('text/plain') is not executable, and

I am newbie in Django, and i was working on a Django app. And i used "media" folder to keep my css and javascript files (i know it's not a good practice) but it was working. Some lines of code ...

stackoverflow.com

 

 

1.  스프링 시큐리티 필터에 걸리는 문제 > 실패

//TokenCheckFilter
 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
  		...
       
if (path.startsWith("/swagger-ui/") || path.startsWith("/v3/api-docs/")) {
            filterChain.doFilter(request, response);
            return;
            
        ...
        
        }
   }

 

2. 인증문제 > 실패

.js파일, .css 들이 401

//CustomSecurityConfig

  private static final List<String> AUTH_WHITELIST = Arrays.asList(
            "/", "/**", "/oauth/**", "/api/**",
            "/actuator/health", "/withdraw", "/mission/**", "/home",
            "/swagger/**", "/swagger-ui/**"
    );

//(생략)

 @Bean
    public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
    ....
    
    
http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/js/**", "/css/**", "/images/**").permitAll()
                .requestMatchers("/v3/api-docs","/api/check-email", "/api/register", "/api/login", "/api/logout", "/api/check-nickname", "/user/profileImage", "/event/**", "/user/**",
                        "/v3/api-docs/**","/swagger-ui/**").permitAll()
                .requestMatchers(AUTH_WHITELIST.stream().toArray(String[]::new)).permitAll()
                .anyRequest().authenticated()
        );
        
   ....
   
   
        return http.build();
    }

 

 

 

여기까지 했을 때 아래 페이지가 나왔다.

드디어 페이지 다운 페이지가 보이기 시작했다. 

 

 

 

3. swaggerconfig 수정 > 성공

//SwaggerConfig

package com.example.rewardservice.common.config;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//http://localhost:3001/swagger-ui/index.html#/
@OpenAPIDefinition(info = @Info(title = "Reward Service",version = "v1"))
@RequiredArgsConstructor
@Configuration
public class SwaggerConfig {
    @Bean
    public GroupedOpenApi chatOpenApi() {
        String[] paths = {"/**"};

        return GroupedOpenApi.builder()
                .group("Reward Service v1")
                .pathsToMatch(paths)
                .build();
    }
}

 

엄청난 삽질 끝에 얻어낸 성공했는데 SwaggerConfig 설정이 문제였던 것 같다. 

 

 

//CustomSecurityConfig
.requestMatchers(AUTH_WHITELIST.stream().toArray(String[]::new)).permitAll()

 

우선 이 코드는 빼도 swagger는 정상적으로 노출된다. 

 

//CustomSecurityConfig
.requestMatchers("/v3/api-docs/**","/swagger-ui/**").permitAll()

 

위 코드가 없으면 페이지 에러가 반환된다

 

    @Configuration
public class WebConfig implements WebMvcConfigurer {
    
    ...
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 이미지 파일 경로 설정
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + imageStoreDir);

//        // Swagger UI 리소스 경로 설정
//        registry.addResourceHandler("/swagger-ui/**")
//                .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/");
    }
    
	...
    
 }

위 주석처리한 코드는 필요없었다.

 

 

    // 로그인과 회원가입 요청시 필터 통과
        if (path.equals("/api/login") || path.equals("/api/register") || path.equals("/api/check-email") || path.equals("/api/check-nickname")  ) {
            filterChain.doFilter(request, response);
            return;
        }


//        if (path.startsWith("/swagger-ui/") || path.startsWith("/v3/api-docs/")) {
//            filterChain.doFilter(request, response);
//            return;
//        }

 

해당 코드가 없으면 아래 오류가 발생한다.

 

 

이렇게 해서 여러 삽질 끝에 해결했다.