Swagger-ui 具有 Spring 安全性

Swagger-ui with Spring security

我有一个带有身份验证服务的简单 REST 应用程序。我尝试向其中添加 swagger 和 swagger-ui,但我只能在 /v2/api-docs 中看到我的端点。 在 swagger-ui.html 中,我只看到端点组,但无法扩展任何列表。

在chrome调试中我看到:

Failed to load resource: the server responded with a status of 401 ()

Uncaught TypeError: Cannot read property 'indexOf' of undefined

并在带有服务器的终端上:

ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Full authentication is required to access this resource

看来我的配置文件缺少某些东西,我尝试了在网上找到的一些解决方案,但仍然没有任何效果。

这是我的代码:

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>

控制器

@RestController
@PreAuthorize("hasRole('USER')")
@RequestMapping(path = "restaurant")
@Api(value="restaurant", description="Example operations for restaurants")
public class RestaurantController {
// endpoints
}

招摇豆

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.tablebooker.restaurantservice.restaurant"))
                .paths(PathSelectors.any())
                .build();
    }
}

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//other methods

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                .permitAll()
                .antMatchers("/api/auth/**")
                .permitAll()
                .antMatchers("/restaurant/**")
                .hasRole("USER")
                .anyRequest()
                .authenticated();

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
    }
}

有什么想法可以让我的配置正常工作吗?

首先你应该注册 swagger 的资源。

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


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

然后因为你正在使用 Spring 安全,也许你应该关闭权限。

   @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**");
        // ignore swagger 
        web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs");
    }

也许你最好使用版本低于2.8.0的swagger,否则你可能不得不面对很多错误。

对我来说,传统的 Weblogic 部署没有任何问题,没有提到 @Override public void configure(WebSecurity web) throws Exception ...只有 @Override protected void configure(HttpSecurity http) throws Exception 就足够了,UI 在 swagger 上是可见的。

但是相同的代码在 Apache Tomcat 服务器上不起作用,因此需要以下代码,

@Override public void configure(WebSecurity web) throws Exception { web.ignoring().mvcMatchers(HttpMethod.OPTIONS, "/**"); // ignore swagger web.ignoring().mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs","/webjars/**"); }

/webjars/** AokoQin 的回答不见了。

在这里回答是因为没有上面的代码我在 Weblogic 上没有遇到任何问题,但只有 Tomcat。我已经在 mvc 配置中通过 ResourceHandlerRegistry 添加了资源。

之前的答案对我有帮助,但不够完整/过时。我遇到了同样的问题,现在可以正常工作了:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @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/");
    }
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  ...

  @Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
        .mvcMatchers("/swagger-ui.html/**", "/configuration/**", "/swagger-resources/**", "/v2/api-docs", "/webjars/**");
  }

  ...

}