swagger cross-domain, 404, pop-up problem solving

Preface

In order to facilitate the front-end testers to test the interfaces I wrote, I specially studied and used swagger before, but I felt very good to use it, but after a period of time, I happily let my front-end colleagues come. When I tested it with this thing, it turned over. To be honest, I was really embarrassed.

After that, I still encountered many problems in the process of reforming. I have encountered these problems before, but I did not think about why I did this at all. This time I encountered a wall in the process of solving. serious.

If you want to see how to configure swagger at the beginning, you can read my two previous articles.
SSM integrates Swagger
front-end interface testing artifact Swagger basic use

404 question

This problem is relatively easy to solve, but since I haven't considered it carefully before, I have been stuck for a long time.

In fact, 404 question is very simple, it means there is no match to the resources we need, as long as we will the resources we need to re-match to go on the line, there are many solutions online are prompted everyone in springmvc的配置文件, add the following lines of code inside the line Up

 <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
 <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

But because I am a project of the SSM framework,
Insert picture description here

I looked at my project path as if there was no path /META-INF/resources/ so, I changed this path to this /WEB-INF/swagger/ , hehe, I still felt like I was after I changed it like this. It's pretty smart, I didn't want to copy it, but then I tested it for a long time and found that it was useless at all.The page still reported a 404 error. After that, I searched for a long time and finally found a blog to make it clear. In fact, the path here is not It does not refer to the path of our project, but refers to the path under our corresponding dependencies. Here, you can understand it by looking at the following figure.
Insert picture description here
So when solving the problem, you still need to investigate more deeply. If you have a 404 error in a springboot project, You need to create an WebMvcConfiginheritance WebMvcConfigurerAdapter, and then add the following code

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    
    
        configurer.enable();
    }
}

Popup problem

If your project uses security frameworks such as shiro or springsecurity, I believe you should know what I am going to say. Obviously your resources will definitely be intercepted, so we need to open the corresponding resources. There are two

  • The configuration file is written through the .xml file.
    Here we only need to add the following code to the filter chain
/v2/api-docs = anon
/swagger-resources/configuration/ui = anon
/swagger-resources = anon
/swagger-resources/configuration/security = anon
/swagger-ui.html = anon
/webjars/** = anon
  • The configuration file is written by the .class file,
    you need to add the following code to the configuration file
public void configure(WebSecurity web)throws Exception{
    
    
web.ignoring().antMatchers("/v2/api-docs",//swagger api json
                            "/swagger-resources/configuration/ui",//用来获取支持的动作
                            "/swagger-resources",//用来获取api-docs的URI
                            "/swagger-resources/configuration/security",//安全选项
                            "/swagger-ui.html",
                            "/webjars/**").permitAll()
}

And I recommend that you use the 2.7.0version of Swagger, because after my own practice, I found that the 2.9.2 version does have the following bugs. I still have the pop-up window with the 2.9.2 version. After using the 2.7.0 version, the problem is successfully solved.

Cross-domain issues

Because after all, our interface is mainly for front-end testers, so we must access our files on his computer, so we must solve the cross-domain problem. There are two main types here.

  • springboot project,
    we only need to add the following code in your web configuration file to achieve cross-domain
@Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        // 添加拦截接口请求处理,
//        registry.addInterceptor(loginInterceptor).addPathPatterns("/api/**");
    }

    /**
     * 拦截后的跨域解决
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("GET",
                "POST", "PUT", "OPTIONS");
    }

    /**
     * 处理拦截前处理检测 授权跨域问题
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    /**
     * @return
     */
    private CorsConfiguration corsConfig() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 请求常用的三种配置,*代表允许所有,当时你也可以自定义属性(比如header只能带什么,只能是post方式等等)
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
  • SSM project
    SSM project has relatively more steps,
    add dependencies
<dependency>
      <groupId>com.thetransactioncompany</groupId>
      <artifactId>cors-filter</artifactId>
      <version>2.5</version>
    </dependency>

Create a cross-domain configuration file, and then add the following code,

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
    
    
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/swagger/**","/swagger-ui.html/**","/swagger-resources/**");
        super.addInterceptors(registry);
    }

    @Bean
    public ProcessInterceptor currentUserMethodArgumentResolver(){
    
    
        return new ProcessInterceptor();
    }

    @Bean
    public ProcessInterceptor authenticationInterceptor(){
    
    
        return new ProcessInterceptor();
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                 .maxAge(3600);
        super.addCorsMappings(registry);
    }
}

Then configure the cross-domain filter in the web.xml file

     <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
      <param-name>cors.allowOrigin</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedMethods</param-name>
      <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
      <param-name>cors.exposedHeaders</param-name>
      <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportsCredentials</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  
  <filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

After the above problems are solved, you should be able to access it normally through the ip of the machine.You
Insert picture description here
can see it here. If you think it is helpful to you, you can pay attention to my official account. The newcomer up needs your support.
Insert picture description here

Guess you like

Origin blog.csdn.net/lovely__RR/article/details/108979835