복붙노트

[SPRING] Springfox swagger-ui.html이 기본 URL을 유추 할 수 없음-쿠키 누락으로 인한

SPRING

Springfox swagger-ui.html이 기본 URL을 유추 할 수 없음-쿠키 누락으로 인한

API Gateway 뒤에 Spring Boot 서비스가 있습니다. Springfox-2.1.2의 이전 버전에서는 swagger-ui.html 페이지를로드 할 때 아무런 문제가 없었습니다. 이것은 Spring Boot 1.4.3.RELEASE와 함께 작동했습니다. 그때부터 부트 1.5.7로 업그레이드하고 Springfox를 2.8.0으로 업그레이드했습니다.

이제 페이지를로드하면 다음과 같은 긴 메시지가있는 경고 상자가 나타납니다.

온라인 검색에 대한 힌트가 있지만 이러한 상황이 우리에게 적용되지 않는 것 같습니다. 예를 들어, 단순히 버전을 되 돌리면 동일한 API 게이트웨이를 통해 다시 작동하기 시작합니다.

트래픽을 추적하면 .html 페이지에서 만든 세 개의 XHR 리소스에 대한 호출이 문제를 일으키는 것으로 보입니다. API 게이트웨이에서 401을 반환합니다. 그리고 그들이 401을 반환하는 이유는 쿠키가 전달되지 않기 때문입니다.

세 가지 통화는 다음과 같습니다.

이 URL을 순수한 브라우저 요청으로로드하면 쿠키가 전송되기 때문에 작동합니다.

HTML이 swagger JSON 및 실제 서비스 호출과 동일한 주소에서 제공되므로 CORS가 적용되는지 의심됩니다.

왜 이런 일이 일어날 지 아십니까? 비슷한 문제에 직면 한 사람이 있습니까? 해결 방법 제안? 미리 감사드립니다.

해결법

  1. ==============================

    1.인증을 위해 건너 뛴 URL을 따라 보안 구성에 추가 ::

    인증을 위해 건너 뛴 URL을 따라 보안 구성에 추가 ::

    private static final String[] AUTH_WHITELIST = {
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**"
    };
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(AUTH_WHITELIST);
    }
    
  2. ==============================

    2.스프링 부트 클래스에서 아래 주석을 추가하면이 문제가 해결되었습니다.

    스프링 부트 클래스에서 아래 주석을 추가하면이 문제가 해결되었습니다.

    swagger 버전을 사용하고 있습니다

     <version>2.9.2</version>
    
  3. ==============================

    3.아래 편집 참조

    아래 편집 참조

    스프링 시큐리티를 사용하십니까?

    그렇다면 아마도 다음과 같은 리소스를 건너 뛸 것입니다. "/ swagger-resources / **", "/swagger-ui.html", "/ v2 / api-docs", "/ webjars / **"

    "/ swagger-resources / **"를 "** / swagger-resources / **"로 변경하십시오.

    swagger에 대한 내 특정 보안 구성은 다음과 같습니다.

    private static final String[] AUTH_LIST = {
            // -- swagger ui
            "**/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**"
    };
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests().antMatchers(AUTH_LIST).authenticated()
        .and()
        .httpBasic().authenticationEntryPoint(swaggerAuthenticationEntryPoint())
        .and()
        .csrf().disable();
    }
    
    @Bean
    public BasicAuthenticationEntryPoint swaggerAuthenticationEntryPoint() {
        BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
        entryPoint.setRealmName("Swagger Realm");
        return entryPoint;
    }
    

    필요 / 원하는 경우 샘플 프로젝트를 GitHub에 보내 보안 / 스 캐거 구성에 대해 더 많이 알 수 있습니다.

    2018/04/10 편집

    이 문제는 springfox의 잘못된 버전으로 인해 발생합니다. 문제를 해결하려면 github에서이 문제를 참조하십시오.

    후손에게 :

    pom.xml에서

    ...
    <repositories>
        <repository>
            <id>swagger</id>
            <name>swagger</name>
            <url>http://oss.jfrog.org/artifactory/oss-snapshot-local</url>
        </repository>
    </repositories>
    ...
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.8.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.8.1-SNAPSHOT</version>
    </dependency>
    ...
    

    WebSecurityConfigAdapter를 확장하는 클래스 :

    @Configuration
    public class WebSecurityConfigEntryPointApplication extends WebSecurityConfigurerAdapter {
    
        private static final List<String> AUTH_LIST = Arrays.asList(
                "/swagger-resources/**",
                "/swagger-ui.html**",
                "/webjars/**",
                "favicon.ico");
    
        @Autowired
        private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/**").authorizeRequests().anyRequest().authenticated()
                    .and()
                    .exceptionHandling()
                    .defaultAuthenticationEntryPointFor(swaggerAuthenticationEntryPoint(), new CustomRequestMatcher(AUTH_LIST))
                    .and()
                    .httpBasic()
                    .authenticationEntryPoint(restAuthenticationEntryPoint)
                    .and()
                    .csrf().disable();
        }
    
        @Bean
        public BasicAuthenticationEntryPoint swaggerAuthenticationEntryPoint() {
            BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
            entryPoint.setRealmName("Swagger Realm");
            return entryPoint;
        }
    
        private class CustomRequestMatcher implements RequestMatcher {
    
            private List<AntPathRequestMatcher> matchers;
    
            private CustomRequestMatcher(List<String> matchers) {
                this.matchers = matchers.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
            }
    
            @Override
            public boolean matches(HttpServletRequest request) {
                return matchers.stream().anyMatch(a -> a.matches(request));
            }
    
        }
    
    }
    

    RestAuthenticationEntryPoint :

    @Component
    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
    }
    
  4. ==============================

    4.이것은 나에게 일어났다. Spring Boot 1.5.16과 Springfox 2.9.1을 사용하고 있었다.

    이것은 나에게 일어났다. Spring Boot 1.5.16과 Springfox 2.9.1을 사용하고 있었다.

    내 application.properties에서 server.servlet-path = / api를 정의했지만 swagger-ui가 정의 된 값을 무시했습니다. 이 작업을 수행하기 위해 많은 다른 방법을 시도했으며 마침내 해결 방법을 찾았습니다.

     @Configuration
     @EnableSwagger2
     public class SwaggerConfiguration extends WebMvcConfigurationSupport {                                    
    
        @Bean
        public Docket apiMonitoramento() { 
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()                                  
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())                          
                    .build()    
                    .apiInfo(apiInfo());
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()              
                    .title("REST API")
                    .description("Servicesx")               
                    .build();
        }
    
        @Override
        protected void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
     }
    

    http : // localhost : 8080 / context / swagger-ui.html에 액세스했지만 해당 구성의 올바른 URL은 http : // localhost : 8080 / context / api / swagger-ui.html입니다.

  5. ==============================

    5.springfox-swagger2 및 springfox-swagger-ui 종속성을 2.9.2로 업그레이드하고 basePackage가 올바르게 제공되는지 확인하십시오.

    springfox-swagger2 및 springfox-swagger-ui 종속성을 2.9.2로 업그레이드하고 basePackage가 올바르게 제공되는지 확인하십시오.

    return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors
                    .basePackage("org.abc.xyz.controller"))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiEndPointsInfo());
    
  6. ==============================

    6.포트 8080으로 시도-8080으로 변경 한 후 나를 위해 일했습니다.

    포트 8080으로 시도-8080으로 변경 한 후 나를 위해 일했습니다.

  7. ==============================

    7.필자의 경우 문제의 원인은 다음과 같습니다.

    필자의 경우 문제의 원인은 다음과 같습니다.

    @ComponentScan(basePackageClasses = {ApplicationRoot.class })
    

    두 개의 Java 파일에서 두 번.

    여분의 것을 제거한 후에 문제가 사라졌습니다.

  8. from https://stackoverflow.com/questions/49155420/springfox-swagger-ui-html-unable-to-infer-base-url-caused-by-missing-cookies by cc-by-sa and MIT license