简体   繁体   English

带有 Spring 安全性的 Swagger-ui

[英]Swagger-ui with Spring security

I have a simple REST application with authentication service.我有一个带有身份验证服务的简单 REST 应用程序。 I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs .我尝试向其中添加 swagger 和 swagger-ui,但我只能在/v2/api-docs中看到我的端点。 In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.swagger-ui.html我只看到一组端点,但我无法扩展任何列表。

In chrome debug I see:在 chrome 调试中,我看到:

Failed to load resource: the server responded with a status of 401 ()加载资源失败:服务器响应状态为 401 ()

Uncaught TypeError: Cannot read property 'indexOf' of undefined未捕获的类型错误:无法读取未定义的属性“indexOf”

and on a terminal with a server:在带有服务器的终端上:

ERROR 10020 --- [nio-5001-exec-3] ctrapJwtAuthenticationEntryPoint : Responding with unauthorized error.错误 10020 --- [nio-5001-exec-3] ctrapJwtAuthenticationEntryPoint:响应未经授权的错误。 Message - Full authentication is required to access this resource消息 - 访问此资源需要完全身份验证

It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.看起来我的配置文件丢失了一些东西,我尝试了一些我在网上找到的解决方案,但仍然没有任何效果。

This is my code:这是我的代码:

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>

controller控制器

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

swagger bean招摇豆

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

SecurityConfig安全配置

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

Any ideas how can I make my configuration work?任何想法如何使我的配置工作?

For me, there was no issue in traditional Weblogic deployment without any mention of @Override public void configure(WebSecurity web) throws Exception ...Only @Override protected void configure(HttpSecurity http) throws Exception was enough and UI was visible on swagger.对我来说,没有任何提及@Override public void configure(WebSecurity web) throws Exception ...在传统的 Weblogic 部署中没有任何问题 ...只有@Override protected void configure(HttpSecurity http) throws Exception就足够了,并且 UI 在 swagger 上可见。

But the same code was not working on Apache Tomcat server so below code was needed ,但是相同的代码在 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/** being missing in answer by AokoQin. /webjars/**在 AokoQin 的回答中缺失。

Answering here because I didn't faced any issues on Weblogic without above code but only Tomcat.在这里回答是因为我没有在没有上述代码的情况下在 Weblogic 上遇到任何问题,而只有 Tomcat。 I already had resources added via ResourceHandlerRegistry in mvc config.我已经通过 mvc 配置中的ResourceHandlerRegistry添加了资源。

First you should registry swagger's resources.首先,您应该注册 swagger 的资源。

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


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

Then cause you're using Spring Security,maybe you should shutdown privileges.然后由于您使用的是 Spring Security,也许您应该关闭权限。

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

And maybe it's better for you to use swagger which the version is under 2.8.0,or you may have to face to lots of bugs.也许你最好使用版本低于 2.8.0 的 swagger,否则你可能不得不面对很多错误。

The previous answers helped me, but are not quite complete / outdated.以前的答案对我有帮助,但还不够完整/过时。 I was facing the same issue and it's working now:我遇到了同样的问题,它现在正在工作:

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

  ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM