sourcecode

Springfox swagger-ui.html이 기본 URL을 추론할 수 없음 - 쿠키 누락으로 인해 발생함

copyscript 2023. 2. 23. 23:00
반응형

Springfox swagger-ui.html이 기본 URL을 추론할 수 없음 - 쿠키 누락으로 인해 발생함

API Spring Boot Spring Boot.- 2.1에서는 Springfox - 2.1.2를 데가 없었습니다.swagger-ui.html스프링 부츠 1.4.3입니다. 1.로, 0으로 했습니다.「Boot 1.5.7」 「Springfox」 2.8.0 「Boot 1.5.7」 「Springfox 2.8.0.

페이지를 로드하면 다음과 같은 긴 메시지가 포함된 경보 상자가 나타납니다.

기본 URL을 유추할 수 없습니다.이는 동적 서블릿 등록을 사용하거나 API가 API 게이트웨이의 배후에 있을 때 흔히 볼 수 있습니다.기본 URL은 모든 스웨거 리소스가 제공되는 루트입니다.예를 들어 http://example.org/api/v2/api-docs에서 api를 이용할 수 있는 경우 기본 URL은 http://example.org/api/입니다.위치를 수동으로 입력하십시오.

인터넷에서 검색해 본 힌트는 있습니다만, 그런 상황은 해당되지 않는 것 같습니다.예를 들어 단순히 버전을 되돌리면 동일한 API 게이트웨이를 통해 다시 작동하기 시작합니다.

트래픽을 추적하면 .html 페이지에 의해 작성된3개의 XHR 리소스에 대한 콜이 문제의 원인이 되고 있는 것 같습니다.API 게이트웨이에서 401을 반환하고 있습니다.그리고 그들이 401을 반환하는 이유는 쿠키가 전달되지 않았기 때문입니다.

다음의 3개의 콜이 있습니다.

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

HTML은 swagger JSON 및 실제 서비스 콜과 동일한 주소에서 서비스되고 있기 때문에 CORS가 적용되는지 의문입니다.

왜 이런 일이 일어나는지 아십니까?비슷한 문제에 직면한 사람이 있나요?회피책을 제안하시겠습니까?잘 부탁드립니다.

보안 구성 추가 - 인증을 위해 건너뛴 다음 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);
}

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

@EnableSwagger2

스웨거 버전을 사용하고 있습니다.

 <version>2.9.2</version>

아래 편집 참조

스프링 보안을 사용하시나요?

그렇다면 다음과 같은 리소스를 건너뛸 수 있습니다(맞습니까?). "/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 편집

이 문제는 spring fox의 잘못된 버전이 원인입니다.이 문제를 해결하려면 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>
...

Web Security Config Adapter를 확장하는 클래스:

@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");
    }
}

이런 일이 있었습니다.SpringBoot 1.5.16과 Springfox 2.9.1을 사용하고 있었습니다.

의 마마 my에서는application.properties했습니다.server.servlet-path=/api하지만, 어찌된 일인지, swag-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 입니다.

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

@ComponentScan(basePackageClasses = {ApplicationRoot.class })

두 개의 Java 파일에 두 번 있습니다.

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

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());

스프링 보안은 이런 질문을 한 게 아니군요마이 프로젝트 Maven 다중 모듈 사용 localhost: 8080/swagger-ui.html에 액세스하면 먼저 SwaggerConf 클래스에 @EnableSwagger2를 추가하고 마지막으로 @EnableSwagger를 SpringBoot 애플리케이션 클래스로 이동합니다.이 문제는 해결되었습니다.첫 번째:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zuoyan."))
                .paths(PathSelectors.any())
                .build();
    }

}

마지막으로:

 @SpringBootApplication(scanBasePackages = {"com.zuoyan.springboot.appmissionhall"})
 @EnableSwagger2
public class ApplicationStartUpApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationStartUpApplication.class, args);
    }

}

특별한 컴포넌트 스캔옵션을 지정하지 않은 경우 Spring Boot Application 클래스(@Spring Boot Application) 계층에 없는 패키지에 @EnableSwagger2 주석을 포함하는 클래스를 포함하면 이 문제가 발생합니다.

"de.oopexpert.app"에서 Spring Boot Application 클래스를 가정하고 @EnableSwagger2 주석 클래스를 ...에 넣습니다.

  • de.oopexpert.app은 동작합니다.
  • de.oopexpert.app.config가 동작합니다.
  • de.oopexpert.config가 작동하지 않음

@ComponentScan(basePackages = {"de.oopexpert"})을 추가하여 계층의 다른 루트를 지정하여 구성 요소 검색 옵션을 조정할 수 있습니다.

https://stackoverflow.com/a/56716898/13347514에서 제공하는 솔루션은 다음과 같습니다.@EnableSwagger2WebMvc ★★★★★★★★★★★★★★★★★」@Import(SpringDataRestConfiguration.class) Main ]([ Main Application Class ])(주 응용 프로그램 클래스)로 를 해결합니다.

@SpringBootApplication
@EnableSwagger2WebMvc
@Import(SpringDataRestConfiguration.class)
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}

자바어Java 11 , 을 사용해 .Java 8

브라우저 캐시를 지웁니다.그것은 나에게 효과가 있었다.

내 Swagger Docket Bean 구성 파일:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class DocketBean implements WebMvcConfigurer {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swagger.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        // enabling swagger-ui part for visual documentation
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

POM에서의 스웨거 의존관계:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

swagger-ui URL:

http://localhost:8080/http-ui.syslog

포트 8080을 사용해 보세요.8080으로 변경한 후에 동작했습니다.

는 ㅇㅇㅇㅇㅇㅇㅇㅇ다를 넣었습니다.@EnableSwagger2WebMvc을 사용하다2.3.0으로 하다BUILD-SNAPSHOT io. springfox 3.0.0-SNAPSHOT. SpringFoxConfig.

package com.telixia.educare.academy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@EnableSwagger2WebMvc
@SpringBootApplication
public class AcademyApplication {

    public static void main(String[] args) {
        SpringApplication.run(AcademyApplication.class, args);
    }

}

, 이 문제는, 「가 원인일 도 있습니다.springfox-swagger-ui ★★★★★★★★★★★★★★★★★」springfox-swagger2이 하지 않습니다.pom.xml예를 들어, 하나를 업데이트했는데 다른 하나를 업데이트하지 않은 경우:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.6.1</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

하셔야 합니다.springfox-swagger-ui ★★★★★★★★★★★★★★★★★」springfox-swagger2같은 버전입니다.

먼저 이들 2개의 의존관계가 추가되었는지 확인하고 @EnableSwagger2에서 메인 SpringBoot Application 클래스에 주석을 붙이면 문제가 해결됩니다.

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

메인 Spring Boot Application 클래스의 스크린샷

기본적인 Spring MVC 어플리케이션(Spring Security 없음)에서도 같은 문제가 있었습니다.

교체했습니다.

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.
        addResourceHandler("/swagger-ui/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
        .resourceChain(false);
  }

와 함께

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.
        addResourceHandler("/swagger-ui/**")
        .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("**/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

  }

그리고 그것은 효과가 있었다.

이 경우 springfox-spring-webmvc 의존관계를 추가하면 문제가 해결되었습니다.

   <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-spring-webmvc</artifactId>
            <version>2.10.5</version>
        </dependency>

도 같은만, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★@EnableSwagger2메인 앱 클래스 위에 있는 것을 수정했습니다.

예:

    @SpringBootApplication
    @EnableSwagger2
    public class AcademyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AcademyApplication.class, args);
        }
    
        @Configuration
        class RestTemplateConfig {
            @Bean
            @LoadBalanced
            public RestTemplate restTemplate() {
                return new RestTemplate();
            }
        }
    
    }

나의 경우, 나의 프로젝트는 스프링 보안이 없는 Maven 다중 모듈을 사용합니다.

  • Spring Boot v2.2.7풀어주다
  • Swagger2 및 Swagger-ui v2.9.2

솔루션은 @Profile() 값을 변경하는 것입니다.프로젝트 리소스 디렉토리에 작성한 구성 프로파일의 올바른 이름을 입력합니다.

첫 번째:

@Configuration
@EnableSwagger2
@Profile({ "dev", "test" })
public class SwaggerConfig {

 private ApiInfo getApiInfo(String title, String desc) {
        return new ApiInfoBuilder().title(title) 
                .description(desc) 
                .version(DOC_VERSION) 
                .termsOfServiceUrl(URL)                         
                .build();
    }

}

마지막:

@Configuration
@EnableSwagger2
// @Profile({ "dev", "test" })
@Profile({ "kf-oracle", "kf-mysql" })
public class SwaggerConfig {

 private ApiInfo getApiInfo(String title, String desc) {
        return new ApiInfoBuilder().title(title) 
                .description(desc) 
                .version(DOC_VERSION) 
                .termsOfServiceUrl(URL)                         
                .build();
    }

}

도 같은도 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★@EnableSwagger2, SwaggerConfig를 을 잊었습니다.@ConfigurationSwaggerConfig 클래스의 클래스레벨에 있습니다그 주석을 달아서 나의 고민을 해결했다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
public class swaggerConfig {

// swagger configuration
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("mention your package name here")).build();
    }
}

하세요.@ComponentScan(basePackages = "mention your root package name here") 파일Application.java에 되어 있습니다.

스웨거에 스웨거 합니다.pom.xml

Swagger의 POM 의존 관계

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

그 후 설치한 Swagger 서드파티를 설정할 차례입니다.따라서 아래의 순서를 따르세요.

1/패키지 작성 및 이름 설정 구성
2/클래스 Swagger Config 만들기
3/아래 코드를 해당 클래스에 설정한 후

@Configuration
public class SwaggerConfig {

@Bean
public Docket SwaggerApi(){
    return  new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
}

}

4/체크 완료@Configuration ★★★★★★★★★★★★★★★★★」@Bean의 표시)
5/메인 메서드 클래스에서 Swagger2를 활성화해야 합니다.
6/사용@EnableSwagger2Swagger를 활성화하기 위한 주석 2
그런 다음 브라우저로 이동하여 swagger UI를 가져와 UI를 확인합니다.이 코드를 사용합니다.http://localhost:8081/swagger-ui.html#/확인하다server.port

혹시라도 의심스러우시다면spring-boot-starter-parent pom.xml낮은 버전으로.

예:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.4</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

프로젝트가 오류 없이 원활하게 실행됩니다.

".yml" 파일에서 다음을 시도합니다.

swagger:
  enable: true

또는 시도하다"swagger.enable=true"".properties"에서

swagger에 /web을 추가할 필요가 있는 입력 상자나 코드 예에 설정되어 있는 URL 패턴을 볼 수 있기 때문에 이 swag 팝업에 대한 솔루션을 찾았습니다.
오류가 있는 팝업

해결 방법

언급URL : https://stackoverflow.com/questions/49155420/springfox-swagger-ui-html-unable-to-infer-base-url-caused-by-missing-cookies

반응형