带有 Spring 安全性的 Swagger-ui

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

I have a simple REST application with authentication service. I tried to add swagger and swagger-ui to it, but I can only see my endpoints in /v2/api-docs. In swagger-ui.html I see only groups of endpoints but I am unable to extend any list.

在 chrome 调试中我看到:

In chrome debug I see:

加载资源失败:服务器响应状态为401()

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

未捕获的类型错误:无法读取未定义的属性indexOf"

Uncaught TypeError: Cannot read property 'indexOf' of undefined

在带有服务器的终端上:

and on a terminal with a server:

ERROR 10020 --- [nio-5001-exec-3] c.t.r.a.p.JwtAuthenticationEntryPoint :响应未经授权的错误.消息 - 访问此资源需要完全身份验证

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

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

It looks like my config files are missing something, I tried few solutions I found on a web but still nothing work.

这是我的代码:

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

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

Any ideas how can I make my configuration work?

推荐答案

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

First you should registry swagger's resources.

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


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

那么由于您使用的是 Spring Security,也许您应该关闭权限.

Then cause you're using Spring Security,maybe you should shutdown privileges.

   @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,否则你可能不得不面对很多错误.

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.

相关文章